我对 jQuery 相当陌生,所以当我从选择下拉列表中选择一个选项时,我试图自动更改单选框的值。但事情并没有按我的计划进行。
例如: 如果我从选择选项中选择“夫人”或“女士”,则具有“女性”值的 radio 的属性应该变为 true。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$('[name="title"]').change(function() {
if ($(this).val() == "Ms." || $(this).val() == "Mrs.") {
$("#female").prop("checked", true);
} else if ($(this).val() == "Mr.") {
$("#male").prop("checked", true);
}
});
</script>
</head>
<body>
<select name="title">
<option value="" disabled selected>Choose your option</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Ms.">Ms.</option>
</select>
<label>Title</label>
<p><b>Gender</b>
<br/>
</p>
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
<input type="radio" name="gender" id="female">
<label for="female">Female</label>
</body>
<html>
最佳答案
您的代码似乎是正确的。尝试仅使用 document.ready,或将其加载到正文末尾。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('[name="title"]').change(function() {
if ($(this).val() == "Ms." || $(this).val() == "Mrs.") {
$("#female").prop("checked", true);
} else if ($(this).val() == "Mr.") {
$("#male").prop("checked", true);
}
});
});
</script>
</head>
<body>
<select name="title">
<option value="" disabled selected>Choose your option</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Ms.">Ms.</option>
</select>
<label>Title</label>
<p><b>Gender</b>
<br/>
</p>
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
<input type="radio" name="gender" id="female">
<label for="female">Female</label>
</body>
<html>
关于javascript - 使用 jquery 将 select 与 radio 链接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40811795/