我期待JavaScript验证表单的复选框,但我无法让我的代码抛出错误消息。
如果选择3daypass
单选按钮,则应选择某个部分#matthewpeckham
中的3个复选框,等等。这是我在onSubmit()上运行的代码:
function chooseDaysCorrect() {
var totalDaysChecked = 0;
var totalDaysChecked = $('#matthewpeckham').find("[type='checkbox']:checked").length;
if (document.getElementById('3daypass').checked && totalDaysChecked != 3) {
alert("Please select enough days for your chosen delegate pass from the CONFERENCE PASS section above");
return false;
}
else if (document.getElementById('2daypass').checked && totalDaysChecked != 2) {
alert("Please select enough days for your chosen delegate pass from the CONFERENCE PASS section above");
return false;
}
else if (document.getElementById('1daypass').checked && totalDaysChecked != 1) {
alert("Please select enough days for your chosen delegate pass from the CONFERENCE PASS section above");
return false;
}
else {
return true;
}
}
("[type='checkbox']:checked").length
是否正确计算已选择的复选框数?我哪里出错?
我还尝试了以下方式在表单Submit上运行该函数,但这也不起作用:
$(document).ready(function() {
$('#classic').submit(function() {
var totalDaysChecked = 0;
var totalDaysChecked = $('#matthewpeckham').find("[type='checkbox']:checked").length;
if (document.getElementById('3daypass').checked && totalDaysChecked != 3) {
alert("Please select enough days for your chosen delegate pass from the CONFERENCE PASS section above");
return false;
}
else if (document.getElementById('2daypass').checked && totalDaysChecked != 2) {
alert("Please select enough days for your chosen delegate pass from the CONFERENCE PASS section above");
return false;
}
else if (document.getElementById('1daypass').checked && totalDaysChecked != 1) {
alert("Please select enough days for your chosen delegate pass from the CONFERENCE PASS section above");
return false;
}
else {
return true;
}
});
});
答案 0 :(得分:1)
我建议使用以下代码,首先像往常一样创建表单,然后在每个复选框中添加一个自定义data- *字段,其中包含要查找的所需值:
HTML:
<form class="classic" id="classic">
<input type="checkbox" id="3daypass" data-expected="3" ></input>
<input type="checkbox" id="2daypass" data-expected="2" ></input>
<input type="checkbox" id="1daypass" data-expected="1" ></input>
<input type="submit" value="click"></input>
</form>
$(document).ready(function() {
$(“form#classic”)。submit(function(){
totalDaysChecked = $("[type='checkbox']:checked").length
$("[type='checkbox']:checked").each(function(index, value) {
if($(value).attr('data-expected') != totalDaysChecked) {
alert("Please select enough days for your chosen delegate pass from the CONFERENCE PASS section above");
} else {
return true
}
});
return false;
}) })