[英]validate before submit and check if 1 of 2 check boxes per group is checked?
我有8個復選框,分為2個組。在第一組中,我有一個標記為checkbox1的復選框和一個標記為checkbox2的復選框。
我想要一個JavaScript代碼,使我能夠檢查表單提交是否已為每個組選中了至少兩個復選框中的一個。
復選框為是,沒有值,因此每個組只能選中一個。
我不希望腳本僅檢查您是否僅選中了一個復選框,因為這將意味着用戶不必檢查另一組復選框中的至少一個其他復選框。
我正在使用IE9,因此該腳本應與IE9兼容。
我怎樣才能做到這一點 ?
這是我的代碼:
$('#form_check').on('submit', function (e) {
if ($("input[id=checkbox1]:checked").length === 0) {
if ($("input[id=checkbox2]:checked").length === 1) {
}else{
if ($("input[id=checkbox2]:checked").length === 0) {
if ($("input[id=checkbox1]:checked").length === 1) {
e.preventDefault();
alert('no way you submit it without checking a box');
return false;
}
});
這可能就是您想要的,如果沒有讓我知道,我會嘗試將其整理得更好一些。
首先,讓我們整理一下代碼。 您似乎有大量的if語句,並且大多數語句都沒有終止。
其次,我給您的印象是,您想檢查是否按下了其中一個,並且至少按下了一個,但不是兩者都按下。
$('#form_check').on('submit', function (e) {
if ($("input[id=checkbox1]:checked").length === 0 && $("input[id=checkbox2]:checked").length === 0) { // if neither is selected && means and
e.preventDefault();
alert('nothing selected');
return false;
}
else if (($("input[id=checkbox1]:checked").length === 1 && $("input[id=checkbox2]:checked").length === 0) || ($("input[id=checkbox2]:checked").length === 1 && $("input[id=checkbox1]:checked").length === 0)) { //if a is selected and b is not OR (||) b is selected but not a
e.preventDefault();
alert('congrats one or other of the check boxes is selected');
return false;
}
else{ //otherwise you must have selected both
e.preventDefault();
alert("you've managed to select BOTH yes and no");
return false;
}
});
您可以使用DIV嵌入每個復選框組,該DIV的類名為“ required”
<form id="form_check">
<div class="required">
<input type="checkbox" id="checkbox1" />Test 1
<input type="checkbox" id="checkbox2" />Test 2
</div>
<div class="required">
<input type="checkbox" id="checkbox3" />Test 3
<input type="checkbox" id="checkbox4" />Test 4
</div>
<input type="submit" value="Submit" />
</form>
此JavaScript(jQuery)將檢查每個“必需”組。 您必須至少選中每個組中的一個復選框。
$('#form_check').on('submit', function (e) {
e.preventDefault();
$('.required').each(function () {
if ( $(this).find('input:checked').length <= 0 ) {
alert('no way you submit it without checking a box');
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.