user3889963 user3889963 - 4 months ago 19
HTML Question

onchange event on radio button

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/

Answer

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