【问题标题】:How to check< 2 and > 4 checkbox in javascript如何在javascript中检查< 2和> 4复选框
【发布时间】:2012-02-16 18:55:50
【问题描述】:

我正在尝试检查用户输入是否选中了 greater than 2less than 4 复选框。

我必须在提交表单之前进行这项检查。

虽然我使用 AlloyUI 进行客户端验证。你可以帮助我使用香草 javascript。

请帮我写代码...

<% for(loop here which generates more than one checkbox) { %>
<form name=".." method=".." action=".." onSubmit="return checkBox();">
  <input type="checkbox" id=".." name=".."/>
</form>
%>

我的 javascript

function checkBox(){
        alert("start");
        var total = 0;
        var max = form.checkcompare.length;
        alert(max);
        for(var idx = 0; idx < max; idx++)
        {
        if(eval("document.compareform.checkcompare[" + idx + "].checked") == true)
        {
            alert("checking");
        total += 1;
        }
        }
        if (total==2 || total==4)
        {
        /*  document.compareform.submit(); */
        alert("success");
        }
        else
        {
            alert('Select minimum of 2 or maximum of 4 Estimates');
        }
        //alert("You selected " + total + " boxes.");
        }

它不起作用..有人可以帮忙..谢谢

【问题讨论】:

    标签: javascript validation checkbox


    【解决方案1】:

    有些事情告诉我你不知道自己在做什么。

    首先,您要为每个复选框创建一个表单。打开表单标签,然后在循环中添加复选框,然后关闭表单。

    现在为您的脚本...

    form 是未定义的,所以你可以得到它的元素。 form.checkcompare 未定义,因此您无法获取其长度。您可能希望在 onSubmit 事件 (onSubmit="return checkBox(this);") 和 function checkBox(form) 中传递 this。然后使用form.querySelectorAll('input[type=checkbox]');

    接下来,你到底为什么要使用邪恶的eval 来获取数组索引?

    好像这还不够,您说您想要“2 到 4 之间”,但您的代码认为“3”无效。

    最后,你不是returning 任何东西。

    固定(和改进)代码:

    function checkBox(form){ 
        var total = 0; 
        var boxes = form.querySelectorAll('input[type=checkbox]:checked').length;
        if (boxes < 2 || boxes > 4)
            return true;
        else { 
            alert('Select minimum of 2 or maximum of 4 Estimates'); 
            return false;
        } 
    }
    

    【讨论】:

    • 我的代码里有它。形成然后循环内。而且我尝试了您的代码,并且表单也被提交而没有任何警报。你能帮我一个忙吗?如果可以的话,把整个 html 发给我。因为我必须更改为 AUI ......这应该有助于我 gr8 的交易。
    【解决方案2】:
    function getNumberOfCheckedCheckboxes ( form ) {
      var returnValue = 0;
      var inputElements = form.getElementsByTagName("input");
      for (var i = 0; i < inputElements.length; i ++) {
        if (inputElements.type == "checkbox") {
          if (inputElments.checked) {
            returnValue ++;
          }
        }
      }
      return returnValue;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2018-03-20
      • 2015-09-01
      • 1970-01-01
      相关资源
      最近更新 更多