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

我可以得到所有这些:

$("form :radio")

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


当前回答

使用$('input[name=“radioName”]').filter(“:checked”).val();对我来说是最好的方式。

经过测试,这是可行的

Form

<form id="myForm">
  <input type="radio" name="radioName" value="Option1"> Option1
  <input type="radio" name="radioName" value="Option2" checked> Option2
  <input type="radio" name="radioName" value="Option3"> Option3
</form>

滑动分页

$(document).ready(function() {
  $('input[name="radioName"]').on('change', function() {
     const val = $(this).filter(":checked").val();
     alert(val);
  })

  // First load check
  const val = $('input[name="radioName"]').filter(":checked").val();
  alert(val);
});

此处示例:https://codepen.io/abinhho/pen/mdLrqbX

其他回答

获取所有收音机:

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

筛选以获取选中的

radios.filter(":checked")

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

在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)。

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

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

在我的例子中,我在一个表单中有两个单选按钮,我想知道每个按钮的状态。以下内容适用于我:

//获取单选按钮值console.log(“radio1:”+$('input[id=radio1]:checked','#toggle form').val());console.log(“radio2:”+$('input[id=radio2]:checked','#toggle form').val());<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><form id=“toggle form”><div id=“radio”><input type=“radio”id=“radio1”name=“radio“checked=”checked“/><label for=”radio1“>绘制单个</label><input type=“radio”id=“radio2”name=“radio”/><label for=“radio2”>全部绘制</label></div></form>