Jquery:获取不同单选按钮组的值

时间:2014-06-11 12:01:22

标签: javascript jquery html

我有两个单选按钮组。这里的问题是,val()返回的结果不一致,似乎输出卡住了一些旧值。我错过了什么?

<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>

javascript是:

$('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/

5 个答案:

答案 0 :(得分:2)

<强> Demo

this.value用于选择javascript中的当前单选按钮值,closest()用于选择父级

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

Fiddle Demo

使用$(this).val()this.value保持简单 - 您需要当前选定的值,但由于您有两组单选按钮,因此从第一组中获取所选值。

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

答案 3 :(得分:1)

试试这个:实际上你正在寻找触发更改事件的相同单选按钮。 因此,只需要检查当前单选按钮的值。

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

答案 4 :(得分:0)

您应该使用以下方式找到当前表格中的所选输入:

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