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

我可以得到所有这些:

$("form :radio")

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


当前回答

在JSF生成的单选按钮(使用<h:selectOneRadio>标记)中,可以执行以下操作:

radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();

其中selectOneRadio ID是radiobutton_ID,表单ID是form_ID。

如图所示,请务必使用name而不是id,因为jQuery使用这个属性(名称由JSF自动生成,类似于控件id)。

其他回答

您可以将:checked选择器与收音机选择器一起使用。

 $("form:radio:checked").val();

此外,检查用户是否未选择任何内容。

var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {           
   radioanswer = $('input[name=myRadio]:checked').val();
}

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>

JQuery获取表单中的所有单选按钮和选中的值。

$.each($("input[type='radio']").filter(":checked"), function () {
  console.log("Name:" + this.name);
  console.log("Value:" + $(this).val());
});

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

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