我有一组同名的复选框。用户需要选择至少一个复选框,如果"其他"被选中," Promotion_Others"文本框是强制性的。
我不知道如何使用所有具有相同名称的复选框执行此操作。
<input type="checkbox" name="Prefer_Promotion[]" value="food_and_beverages_discounts" >Food & beverages discounts</label>
<input type="checkbox" name="Prefer_Promotion[]" value="complimentary_hotel_facilities">Complimentary hotel facilities</label>
<input type="checkbox" name="Prefer_Promotion[]" value="complimentary_gym_access">Complimentary gym access</label>
<input type="checkbox" name="Prefer_Promotion[]" value="others">Others</label>
<input type="text" class="form-control" name="Promotion_Others" value="" maxlength="50"/>
答案 0 :(得分:0)
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function () {
$('#mysubmit').click(function () {
if ($('input[type=checkbox]').is(':checked')) {
// atleast one checkbox checked, do something...
// now check seleted is othere
$('input[type=checkbox]input:checkbox:checked').each(function () {
var value = $(this).attr('value');
if ('others' === value) {
var others_value = $('.form-control').val();
if (!others_value) {
alert('Please fill text field');
return false;
} else
return true;
}
});
}
});
});
</script>
</head>
<body>
<form id="myform">
<input type="checkbox" name="Prefer_Promotion[]" value="food_and_beverages_discounts" >Food & beverages discounts</label>
<input type="checkbox" name="Prefer_Promotion[]" value="complimentary_hotel_facilities">Complimentary hotel facilities</label>
<input type="checkbox" name="Prefer_Promotion[]" value="complimentary_gym_access">Complimentary gym access</label>
<input type="checkbox" name="Prefer_Promotion[]" value="others">Others</label>
<input type="text" class="form-control" name="Promotion_Others" value="" maxlength="50"/>
<input type="button" value="submit" id="mysubmit"/>
</form>
</body>
</html>
试试这个代码段。评论是否需要帮助