我有两个单选按钮,希望发布所选按钮的值。如何使用jQuery获取值?

我可以得到所有这些:

$("form :radio")

我如何知道选择了哪一个?


当前回答

**请尝试以下示例以检查选中的单选按钮**

<script>
    $('#form1 input').on('change', function() {
       alert($('input[name=age]:checked', '#form1 ').val()); 
    });
</script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    <form id="form1">
      <input type="radio" name="age" value="18" /> 18 <br />
      <input type="radio" name="age" value="20" /> 20 <br />
      <input type="radio" name="age" value="22" /> 22 <br />
    </form>

其他回答

如果您已经引用了单选按钮组,例如:

var myRadio = $("input[name=myRadio]");

使用filter()函数,而不是find()。(find()用于查找子元素/子元素,而filter()用于搜索所选内容中的顶级元素。)

var checkedValue = myRadio.filter(":checked").val();

注意:这个答案最初是在纠正另一个建议使用find()的答案,但后来似乎有所改变。find()对于已经引用了容器元素但没有引用单选按钮的情况仍然有用,例如:

var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();

这应该是有效的:

$("input[name='radioName']:checked").val()

注意输入周围使用的“”:已检查,而不是像Peter J的解决方案那样的“”

Try

myForm.myOption.value

函数检查(){console.log(myForm.myOption.value);}<form id=“myForm”><input-type=“radio”name=“myOption”value=“1”>1<br><input-type=“radio”name=“myOption”value=“2”>2<br><input-type=“radio”name=“myOption”value=“3”>3<br></form><button onclick=“check()”>check</button>

要获取id为myForm的表单的选定radioName项的值,请执行以下操作:

$('input[name=radioName]:checked', '#myForm').val()

下面是一个示例:

$('#myForm input').on('change',function(){alert($('input[name=radioName]:checked','#myForm').val());});<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><form id=“myForm”><fieldset><legend>选择radioName</legend><label><input-type=“radio”name=“radioName”value=“1”/>1</label><br/><label><input-type=“radio”name=“radioName”value=“2”/>2</label><br/><label><input-type=“radio”name=“radioName”value=“3”/>3</label><br/></fieldset></form>

要获取使用类的所选收音机的值,请执行以下操作:

$('.class:checked').val()