我想在单选按钮上进行jQuery验证,但是我无法制作工作代码。
我编写了此代码,但仅此一个单选按钮起作用。
$(document).ready(function() {
$('#radio1').change(function() {
$("#lhr1").prop("checked", true)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<h2 align="center"><b><i>Form Validation Assignment</i></b></h2>
<form id="vald" class="form-horizontal" action="">
</div>
<div class="form-check form-check-inline" id="radio1">
<label class="control-label col-sm-2" for="name">Gender</label>
<div class="container">
<label class="radio-inline">
<input type="radio" name="optradio" id="male">Male
</label>
<label class="radio-inline">
<input type="radio" name="optradio" id="female">Female
</label>
</div>
</div>
<input type="checkbox" name="lhr" value="lhr" id="lhr1"> You can go Lahore<br>
<input type="checkbox" name="mtn" value="mtn" id="mtn1">You can go Multan<br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" id="add">Submit</button>
</div>
</div>
</form>
</div>
如果我选择“男性”(单选按钮),则应选中复选框(“你可以去木尔坦”);如果我选择“女性”(单选按钮),则应选择“(你可以去拉合尔”)。
答案 0 :(得分:0)
这应该可以完成
$(document).ready(function(){
$('#male').click(function(){
$('#mtn1').prop("checked", $(this).is(':checked'));
});
$('#female').click(function(){
$('#lhr1').prop("checked", $(this).is(':checked'));
});
});
答案 1 :(得分:0)
仅(略)修改代码,这也应该起作用。
$(document).ready(function() {
$('#radio1').change(function() {
// Get the currently selected gender
let gender = $("input[name=optradio]:checked").attr("id");
// Check checkboxes based on gender
$("#lhr1").prop("checked", gender === "male")
$("#mtn1").prop("checked", gender === "female")
});
});
答案 2 :(得分:0)
将data
属性用于诸如此类的男性和女性输入会更容易。
<input type="radio" name="optradio" id="female" data-check-id="mtn1">
$(document).ready(function() {
$('[name="optradio"]').change(function() {
$('#lhr1 , #mtn1').prop('checked' , false);
$('#'+$(this).attr('data-check-id')).prop('checked' , true);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<h2 align="center"><b><i>Form Validation Assignment</i></b></h2>
<form id="vald" class="form-horizontal" action="">
</div>
<div class="form-check form-check-inline" id="radio1">
<label class="control-label col-sm-2" for="name">Gender</label>
<div class="container">
<label class="radio-inline">
<input type="radio" name="optradio" id="male" data-check-id="lhr1">Male
</label>
<label class="radio-inline">
<input type="radio" name="optradio" id="female" data-check-id="mtn1">Female
</label>
</div>
</div>
<input type="checkbox" name="lhr" value="lhr" id="lhr1"> You can go Lahore<br>
<input type="checkbox" name="mtn" value="mtn" id="mtn1">You can go Multan<br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" id="add">Submit</button>
</div>
</div>
</form>
</div>