[英]How do I check which radio button is selected when there are multiple radio buttons with the same name? (using jquery)
<form class="responses">
<input type="radio" name="choice" value="0">False</input>
<input type="radio" name="choice" value="1">True</input>
</form>
Have tried: 试过:
$('[name="choice"]').is(':checked'))
If either is checked it returns true, if neither is checked returns false, but I need to see which one is checked. 如果选中其中之一,则返回true,如果两者都未选中则返回false,但我需要查看哪一个被选中。
I am creating choices dynamically, and am not giving each an ID. 我正在动态创建选择,而不是给每个ID。
使用以下代码,您将获得已检查的radio元素的DOM
$("[name=choice]:checked")
The following code will give the value of the checked radio button. 以下代码将给出选中的单选按钮的值。 If nothig is checked it will give undefined.
如果未选中nothig,则将给出undefined。 Put this snippet inside a function and call the function on checking radio button
将此代码段放在函数中,并在选中单选按钮时调用该函数
$("input[name='choice']:checked").val()
If you want to know the selected value use 如果您想知道所选值的使用方法
$("input:radio[name='choice']:checked").val();
If you want to know which radio button is selected use 如果您想知道选择了哪个单选按钮,请使用
var radioButton = $("input:radio[name='choice']");
var selectedIndex = radioButton.index(radioButton.filter(':checked'));
Other answers are the perfect one , this can be an another approach 其他答案是完美的,这可能是另一种方法
HTML : HTML:
<form class="responses">
<input type="radio" name="choice" class="my_radio" value="0">False</input>
<input type="radio" name="choice" class="my_radio" value="1">True</input>
</form>
JQUERY: JQUERY:
$('.my_radio').click(function(){
alert($(this).val());
});
try this: 尝试这个:
$('input[name=choice]:checked', '#myForm').val()
Script: 脚本:
$( "#myForm input" ).on( "change", function() {
$( "#log" ).html( $( "input[name=choice]:checked" ).val() + " is checked!" );
});
HTML: HTML:
<form id="myForm">
<input type="radio" name="choice" value="0">False</input>
<input type="radio" name="choice" value="1">True</input>
</form>
<div id="log"></div>
$( "#myForm input" ).on( "change", function() { $( "#log" ).html( $( "input[name=choice]:checked" ).val() + " is checked!" ); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="myForm"> <input type="radio" name="choice" value="0">False</input> <input type="radio" name="choice" value="1">True</input> </form> <div id="log"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.