验证具有数组作为名称参数的复选框

时间:2013-06-22 22:22:38

标签: javascript html

我曾经使用如下代码验证复选框表单:

<div>
  <form action="survey.php" method="post" name="survey"> 
  <span class="form"><input type="checkbox" name="event1" onClick="return countMarketing()">Event1</span>
  <span class"form"><input type="checkbox" name="event2" onClick="return countMarketing()">Event2</span>
  <span class"form"><input type="checkbox" name="event3" onClick="return countMarketing()">Event2</span>
  <!-- other forms -->
  </form>
</div>

这样的javascript验证(限制复选框的数量):

function countMarketing() {

        var NewCountMarketing = 0

        if (document.survey.event1.checked)
        {NewCountMarketing = NewCountMarketing + 1}

        if (document.survey.event2.checked)
        {NewCountMarketing = NewCountMarketing + 1}

        if (document.survey.event3.checked)
        {NewCountMarketing = NewCountMarketing + 1}
        if (NewCountMarketing == 3)
        {
            alert('Please choose only two')
            document.survey; return false;
        }
    }

这样的验证有效。但是现在,说我使用php来提交,如何在JS中检查表单的名称是否是这样的:

 <input type="checkbox" name="events[]" id="event1" onClick="return countMarketing()">Event1

我试图将JS改为:

if (document.survey.events[].checked)
    {code here}

if (document.survey.getElementByName('events[]').checked)
    {code here}

if (document.survey.getElementById('event1').checked)
    {code here}

但它不起作用..任何人都可以对此有所了解吗?非常感谢你:))

2 个答案:

答案 0 :(得分:1)

如果你实际上在使用jQuery,你可以这样做:

在使用此功能之前,请确保在文档中包含jQuery。在尝试运行该函数之前已加载文档。

function countMarketing() {

  if( $('input[name="events[]"]').filter(':checked').length > 2 ) {
    alert('Please choose only two');
  }

}

答案 1 :(得分:1)

首先删除inline events declaration并将其移至external Javascript filescript block

您始终可以使用bracket Notation来访问此类属性

document.survey["events[]"]

<强>代码

    var elems = document.survey,
    checkboxNames = ["event1[]", "event2[]", "event3[]"];

for (var i = 0; i < checkboxNames.length; i++) {
    bindClick(elems[checkboxNames[i]]);
}

function bindClick(elem) {
    elem.addEventListener('click', countMarketing);
}

function countMarketing() {

    var NewCountMarketing = 0
    var latest;
    for (var i = 0; i < checkboxNames.length; i++) {
        if (elems[checkboxNames[i]].checked) {
            latest = elems[checkboxNames[i]];
            NewCountMarketing++;
        }
    }

    if (NewCountMarketing == 3) {
        latest.checked = false;               
        alert('Please choose only two')
        document.survey;
        return false;
    }
}

<强> Check Fiddle