简体   繁体   中英

Jquery: Getting the values of different radio buttons groups

I have two radio button groups. The problem here is, the result returned by the val() is not consistent, and it seems the output is stuck with some old value. What am I missing?

<form id="form_1">
    <div id="myForm_1">

        <input type="radio" name="radioName_1" value="1" /> 1 <br />
        <input type="radio" name="radioName_1" value="2" /> 2 <br />
        <input type="radio" name="radioName_1" value="3" /> 3 <br />
    </div>
</form>
<hr>
<form id="form_2">
    <div id="myForm_2">
        <div id="new">
            <input type="radio" name="radioName_2" value="4" /> 4 <br />
            <input type="radio" name="radioName_2" value="5" /> 5 <br />
            <input type="radio" name="radioName_2" value="6" /> 6 <br />
        </div>
    </div>
</form>

And the javascript is:

$('input').on('change', function() {
   var question = $(this).closest("form").attr("id");
   var selected = $('input[name^=radioName]:checked').val();
   var msg = question + " " + selected;
   alert(msg); 
});

http://jsfiddle.net/RhnvU/1847/

Demo

this.value used for select current radio button value in javascript and closest() used for select parent

  $('input').on('change', function () {
    var question = $(this).closest("form").prop("id");
    var selected = this.value;
    var msg = question + " " + selected;
    alert(msg);
});

try

$('input').on('change', function() {
 var question = $(this).closest("form").attr("id");
  var selected = $(this).val();
  var msg = question + " " + selected;
  alert(msg); 
});

Fiddle Demo

Use $(this).val() or this.value to keep it simple - You need current selected value, but as you have two sets of radio buttons, it was getting the selected value from the first set.

$('input').on('change', function() {
   var question = $(this).closest("form").prop("id");
   var selected = $(this).val();   //or this.value
   var msg = question + " " + selected;
   alert(msg); 
});

Try this : Actually you are looking for the same radio button for which change event fired. So need to check value of current radio button only.

$('input').on('change', function() {
   var question = $(this).closest("form").attr("id");
   var selected =  $(this).val();
   var msg = question + " " + selected;
   alert(msg); 
});

You should find the selected input in current form using:

$('input').on('change', function() {
 var question = $(this).closest("form").attr("id");
 var selected = $(this).val();
 var msg = question + " " + selected;
 alert(msg); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM