1

我正在寻找 JavaScript 验证表单的复选框,但我无法让我的代码抛出错误消息。

如果选择单选按钮,则应选择3daypass某个部分中的 3 个复选框,等等。这是我在 onSubmit() 上运行的代码:#matthewpeckham

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计算已选择复选框数量的正确方法是什么?我哪里出错了?

我还尝试了以下在表单提交上运行函数的方法,但这也不起作用:

$(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;
    }

});

});
4

1 回答 1

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; 

}) })

在这里试试:http: //jsbin.com/ipazow/1/

于 2013-01-23T12:41:45.123 回答