我将如何改变这个Javascript代码

时间:2012-02-22 01:07:03

标签: javascript javascript-events validation

我需要添加什么才能根据已选择的复选框进行验证?我希望用户在提交数据之前至少选择两个复选框。这是我的javascript代码:

    <script type="text/javascript" language="JavaScript">

function checkCheckBoxes(theForm) {
    if (
    theForm.Conservatives.checked == false &&
    theForm.Labour.checked == false &&
    theForm.LiberalDemocrats.checked == false) 
    {
        alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
        return false;
    } else {    
        return true;
    }
}

</script> 

当前的javascript代码仅验证是否有任何复选框已被剔除,但我希望它验证两个复选框。

6 个答案:

答案 0 :(得分:2)

只需计算检查的数量,看它是否小于2.

function checkCheckBoxes(theForm) {
    var cnt = 0;
    if (theForm.Conservatives.checked) ++cnt;
    if (theForm.Labour.checked) ++cnt;
    if (theForm.LiberalDemocrats.checked) ++cnt;
    if (cnt < 2) {
        alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
        return false;
    } else {    
        return true;
    }
}

答案 1 :(得分:0)

只要您只担心这三个复选框并且您不想使用JavaScript库,我能想到的最简单的事情就是:

var checkedBoxes = [];

if(theForm.Conservatives.checked) 
    checkedBoxes.push(theForm.Conservatives);
if(theForm.Labour.checked)
    checkedBoxes.push(theForm.Labour);
if(theForm.LiberalDemocrats.checked)
    checkedBoxes.push(theForm.LiberalDemocrats;

// two or more boxes are checked
if(checkedBoxes.length < 2){
    alert('Choose at least two parties.');
}
else {
    // Do stuff with checkedBoxes.
}

此方法不仅会为您提供已检查项目数量的计数,而且还允许您在以后的代码中仅访问选中的复选框。

答案 2 :(得分:0)

你可以这样做:

if (theForm.Conservatives.checked +
    theForm.Labour.checked +
    theForm.LiberalDemocrats.checked) < 2)
{
 alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
 return false;
} else {    
 return true;
}

答案 3 :(得分:0)

function checkCheckBoxes(theForm) {
  var opts = ["Conservatives","Labour","LiberalDemocrats"],
      selected = 0;

  for (var i = 0; i < opts.length; i++) {
    if (theForm[opts[i]].checked)
      selected++;
  }
  if (selected < 2) {
    alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
    return false;
  } else {    
    return true;
  }
}

答案 4 :(得分:0)

function checkCheckBoxes(theForm) {
 if(theForm.Conservatives.checked + theForm.Labour.checked + theForm.LiberalDemocrats.checked > 1)return true;
 alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
 return false;
}

答案 5 :(得分:0)

function checkCheckBoxes(theForm) {
    var checkboxes = [theForm.Conservatives, theForm.Labour, theForm.LiberalDemocrats];
    var checked = 0;
    checkboxes.forEach(function(el){ 
                              if (el.checked) checked++;
                       });
    if (checked < 2) 
    {
        alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
        return false;
    } else {    
        return true;
    }
}