我有两个单选按钮,希望发布所选按钮的值。如何使用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>

其他回答

要获取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>

获取所有收音机:

var radios = jQuery("input[type='radio']");

筛选以获取选中的

radios.filter(":checked")

您需要使用:checked选择器访问:

检查此文档:

https://api.jquery.com/checked-selector/

例如:

$('input[name=radioName]:checked','#myForm').val()$('#myForm input').on('change',function(){$('#val').text($('input[name=radioName]:checked','#myForm').val());});#值{颜色:#EB0054;字体大小:1.5em;}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><h3>无线电值:<span id=“val”><span></h3><form id=“myForm”><input type=“radio”name=“radioName”value=“a”>a<br><input-type=“radio”name=“radioName”value=“b”>b<br><input-type=“radio”name=“radioName”value=“c”>c<br></form>

如果在一个表单上只有一组单选按钮,jQuery代码如下所示:

$( "input:checked" ).val()

要检索JavaScript数组中的所有单选按钮值,请使用以下jQuery代码:

var values = jQuery('input:checkbox:checked.group1').map(function () {
    return this.value;
}).get();