繁体   English   中英

我将如何更改此 Javascript 代码以验证数据

[英]How Would I Alter This Javascript Code to validate the data

我需要添加什么才能根据已选择的复选框数量进行验证? 我希望用户在提交数据之前至少选择两个复选框。 这是我的 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 代码仅验证是否选择了任何复选框,但我希望它验证两个复选框。

只需计算检查了多少,看看它是否小于 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;
    }
}

只要您只担心这三个复选框并且不想使用 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.
}

此方法不仅会为您提供已选中项目数的计数,而且还允许您稍后在需要时仅访问代码中的选中框。

你可以做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM