根据单选按钮选项验证所选复选框的数量

时间:2013-01-23 11:22:23

标签: javascript jquery validation

我期待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;
    }

});

});

1 个答案:

答案 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; 

}) })

在此处试试:http://jsbin.com/ipazow/1/