我有两个单选按钮,希望发布所选按钮的值。如何使用jQuery获取值?
我可以得到所有这些:
$("form :radio")
我如何知道选择了哪一个?
我有两个单选按钮,希望发布所选按钮的值。如何使用jQuery获取值?
我可以得到所有这些:
$("form :radio")
我如何知道选择了哪一个?
当前回答
获取所有收音机:
var radios = jQuery("input[type='radio']");
筛选以获取选中的
radios.filter(":checked")
其他回答
JQuery获取表单中的所有单选按钮和选中的值。
$.each($("input[type='radio']").filter(":checked"), function () {
console.log("Name:" + this.name);
console.log("Value:" + $(this).val());
});
这应该是有效的:
$("input[name='radioName']:checked").val()
注意输入周围使用的“”:已检查,而不是像Peter J的解决方案那样的“”
试试看-
var radioVal = $("#myform").find("input[type='radio']:checked").val();
console.log(radioVal);
要获取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>
此解决方案不需要jQuery。
const RADIO_NAME = "radioName";
const radios = Array.from(document.getElementsByName(RADIO_NAME));
const checkedRadio = radios.filter(e=>e.checked);
这使用jQuery:
const radios = Array.from($(`[name=${RADIO_NAME}`));
const checkedRadio = radios.filter(e=>e.checked);
jQuery添加了这里不需要的额外抽象层。
您还可以使用:
const radios = Array.from(document.querySelectorAll(`[name=${RADIO_NAME}`));
const checkedRadio = radios.filter(e=>e.checked)[0];
但getElementsByName足够简单明了。