Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  34] [ 3]  / answers: 1 / hits: 34476  / 8 Years ago, mon, september 19, 2016, 12:00:00

I am trying to achieve something simple. Basically I have 3 radio groups and onchange of either one of those group, I want to get the values of all the radio groups and display on an alert box.



My code is as follows



html



<input type=radio name=ac value=yes> YES
<input type=radio name=ac value=no> NO
<br>
<input type=radio name=tier value=normal> normal
<input type=radio name=tier value=deluxe> deluxe
<br>
<input type=radio name=cap value=big> big
<input type=radio name=cap value=small> small


js



$(input[type=radio]).on(change,function(){
var ac=$(input[type=radio][name=ac]).val();
var tier=$(input[type=radio][name=tier]).val();
var cap=$(input[type=radio][name=cap]).val();

alert(ac+ +tier+ +cap);
});


I have a jsfiddle here too https://jsfiddle.net/5fg6by8m/



ON the fiddle, it seems like the event doesn't fire at all, while on my localhost server using mozilla to browse I always get the values of the first items of each group in my alert box (yes normal big). I might be doing some silly mistake. Please help me correct this.



Thanks in advance...



edit
corrected fiddle
https://jsfiddle.net/5fg6by8m/4/


More From » jquery

 Answers
72

You can use below code. you have to use :checked psudo selector





$(document).on(change,input[type=radio],function(){
var ac=$('[name=ac]:checked').val();
var tier= $('[name=tier]:checked').length>0? $('[name=tier]:checked').val():;
var cap=$('[name=cap]:checked').length>0 ?$('[name=cap]:checked').val():;

alert(ac+ +tier+ +cap);
});

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js></script>
<input type=radio name=ac value=yes> YES
<input type=radio name=ac value=no> NO
<br>
<input type=radio name=tier value=normal> normal
<input type=radio name=tier value=deluxe> deluxe
<br>
<input type=radio name=cap value=big> big
<input type=radio name=cap value=small> small




[#60673] Friday, September 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nikhilc

Total Points: 128
Total Questions: 100
Total Answers: 89

Location: Mali
Member since Sat, Feb 12, 2022
2 Years ago
;