我想按用户选择显示单选按钮值,但是在警报时我没有得到这些值。
我还想将单选按钮值显示为图像。.例如,当用户选择“男性”时,“男性”图片显示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form id="test">
<h4>Gender</h4>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<h4>Occupation</h4>
<input type="radio" name="occupation" value="PvtJob">Pvt. Job<br>
<input type="radio" name="occupation" value="Govt">Govt. Employee<br>
<h4>Loan Type</h4>
<input type="radio" name="loan" value="Personal">Personal Loan<br>
<input type="radio" name="loan" value="Health">Health Loan<br><br>
<button class="btn btn-primary pull-right place-order-button" name="submit" value="submit" onclick="return myFunction()" type="submit" >Finish</button>
</form>
</body>
<script type="text/javascript">
function myFunction() {
var radioButtons =["gender","occupation","loan"];
for( var x = 0; x < radioButtons.length; x ++) {
if ($('input[name = "'+radioButtons[x]+'"]:checked','#test').val()) {
alert("You checked " + $('input[name = "'+radioButtons[x]+'"]:checked','#test').attr('id'));
alert("Value is " + $('input[name = "'+radioButtons[x]+'"]:checked','#test').val());
}
}
}
</script>
</html>
最佳答案
在代码中包含jquery,输入中提到了snot属性ID。另外,您的代码中也没有ID(例如test)。
您也不需要再次重复选择器,只需使用$(this)
请尝试以下代码段。
function myFunction() {
var radioButtons =["gender","occupation","loan"];
for( var x = 0; x < radioButtons.length; x ++) {
if ($('input[name = "'+radioButtons[x]+'"]:checked').val()) {
alert("Value is " + $(this).val());
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="test">
<h4>Gender</h4>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<h4>Occupation</h4>
<input type="radio" name="occupation" value="PvtJob">Pvt. Job<br>
<input type="radio" name="occupation" value="Govt">Govt. Employee<br>
<h4>Loan Type</h4>
<input type="radio" name="loan" value="Personal">Personal Loan<br>
<input type="radio" name="loan" value="Health">Health Loan<br><br>
<button class="btn btn-primary pull-right place-order-button" name="submit" value="submit" onclick="return myFunction()" type="submit" >Finish</button>
</form>
</body>