我有两个单选按钮,希望发布所选按钮的值。如何使用jQuery获取值?
我可以得到所有这些:
$("form :radio")
我如何知道选择了哪一个?
我有两个单选按钮,希望发布所选按钮的值。如何使用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>
其他回答
要获取使用类的所选收音机的值,请执行以下操作:
$('.class:checked').val()
我编写了一个jQuery插件,用于设置和获取单选按钮值。它还尊重他们身上的“变化”事件。
(function ($) {
function changeRadioButton(element, value) {
var name = $(element).attr("name");
$("[type=radio][name=" + name + "]:checked").removeAttr("checked");
$("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
$("[type=radio][name=" + name + "]:checked").change();
}
function getRadioButton(element) {
var name = $(element).attr("name");
return $("[type=radio][name=" + name + "]:checked").attr("value");
}
var originalVal = $.fn.val;
$.fn.val = function(value) {
//is it a radio button? treat it differently.
if($(this).is("[type=radio]")) {
if (typeof value != 'undefined') {
//setter
changeRadioButton(this, value);
return $(this);
} else {
//getter
return getRadioButton(this);
}
} else {
//it wasn't a radio button - let's call the default val function.
if (typeof value != 'undefined') {
return originalVal.call(this, value);
} else {
return originalVal.call(this);
}
}
};
})(jQuery);
将代码放在任何位置以启用加载项。那就享受吧!它只是重写默认的val函数而不破坏任何东西。
你可以访问这个jsFiddle来尝试它的实际操作,看看它是如何工作的。
不停摆弄
使用$('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
这很好
$('input[type="radio"][class="className"]:checked').val()
工作演示
:checked选择器适用于复选框、单选按钮和选择元素。仅对于select元素,请使用:selected选择器。
API:选中的选择器
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>