[英]Get the value of the selected radio button
I have defined a set of radio buttons in HTML in a form as follows. 我以如下形式在HTML中定义了一组单选按钮。 The name of my form is "MyForm".
我的表单的名称是“ MyForm”。 When Female is selected, I want the value of a variable to be equal to "Female".
当选择“女性”时,我希望变量的值等于“女性”。
<fieldset data-role="controlgroup" data-type="horizontal" id="gender" name="gender">
<legend>Gender :</legend>
<input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked" />
<label for="radio-choice-1">Male</label>
<input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2"/>
<label for="radio-choice-2">Female</label>
</fieldset>
I tried as var 我尝试过var
genderValue = $('input[name=gender]:checked', '#MyForm').val()
But this is not working. 但这是行不通的。 What is the correct way?
正确的方法是什么?
you can store the values( female
, ...
), in value attribute of the inputs, based on your markup you can try the following: 您可以将值(
female
, ...
)存储在输入的value属性中,根据您的标记,您可以尝试以下操作:
$('input[name="radio-choice-1"]').change(function(){
var genderValue = $(this).next('label').text()
})
$('input[name="radio-choice-1"]').change(function(){
var genderValue = this.value
})
$('input[name="radio-choice-1"]').change(function(){ var genderValue = this.value })
Your issue has been solved as below: 您的问题已解决,如下所示:
HTML: HTML:
<form id="MyForm" name="MyForm" method="post">
<fieldset>
<legend>
Gender
</legend>
<div id="panel">
<input type="radio" name="radio-choice" id="radio-choice-1" value="choice-1" />
<label for="radio-choice-1">
Male
</label>
<input type="radio" name="radio-choice" id="radio-choice-2" value="choice-2" />
<label for="radio-choice-2">
Female
</label>
</div>
<div id="result">
</div>
</fieldset>
</form>
jQuery: jQuery的:
$(function() {
$('input[name="radio-choice"]').change(function() {
var genderValue = $(this).next('label').text();
$("#result").html("<p> You have selected " + genderValue + ".");
})
});
I have done bins on http://codebins.com/bin/4ldqpaa 我已经在http://codebins.com/bin/4ldqpaa上完成了垃圾箱
This might helpful to someone, Here is another way to retrieve selected radio button value 这可能对某人有所帮助,这是检索所选单选按钮值的另一种方法
var gender = $('input[name="radio-choice-1"]:checked').val();
Setting id to radio buttons is optional here. 在此处将id设置为单选按钮是可选的。
Happy coding!.... 祝您编程愉快!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.