简体   繁体   English

使用javascript验证动态数量的复选框

[英]validate a dynamicnumber of checkboxes using javascript

I have some ASP code which presents any where from 1-any number of checkboxes (which are named the same) on the page. 我有一些ASP代码,可以显示页面上任意数量的复选框(名称相同)中的任意位置。 This validation does work however I think its a bit weak: 这种验证确实有效,但是我认为它有点弱:

   if (document.getElementById('selectedDocs').checked)
   {
       //this is here to handle the situation where there is only one checkbox being displayed
   }
   else
  {
      var checked = false; 
  var field = myForm.selectedDocs; 
  for(var j = 0; j < field.length; j++)
  { 
     if(field[j].checked == true)
     { 
        checked = true; 
        break; 
     } 
  } 
  if(!checked)
  { 
     alert("You have not ticked any options.  At least one must be selected to proceed!") 
     return false; 
  }    
}

I was working with the code in the else block but this only works when there is more than one checkbox. 我在else块中使用代码,但这仅在有多个复选框时有效。 It ignores the fact I have ticked the one single option when there is only one. 它忽略了只有一个选项时我已勾选了一个选项的事实。 So I placed the code inside the if section......Although it woks its a bit of a hack, can someone kindly improve it for me? 因此,我将代码放在了if部分中……虽然它有点w,但有人可以为我改进吗?

Thanking you... 感谢您...

Use: 采用:

var field = myForm.getElementsByName('selectedDocs');

This always returns a NodeList that you can iterate over. 这总是返回可以迭代的NodeList。

If they are in a form and all have the same name, they can be accessed as a collection that is a property of the form. 如果它们在表单中并且都具有相同的名称,则可以将它们作为表单的属性来作为集合进行访问。 So given: 因此给出:

<form id="f0" ...>
  <input type="checkbox" name="cb0" ...>
  <input type="checkbox" name="cb0" ...>
  <input type="checkbox" name="cb0" ...>
  ...
</form>

All the following return a reference to the form: 以下所有内容均返回对表单的引用:

var form = document.getElementById('f0');

var form = document.forms['f0'];

var form = document.forms[0];  // if first form in document

and and all the following return a collection of the checkboxes named "cb0": 并且所有以下内容返回名为“ cb0”的复选框的集合:

var checkboxes = form.cb0

var checkboxes = form['cb0'];

var checkboxes = form.elements.['cb0'];

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

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