简体   繁体   English

验证-至少选中一个复选框

[英]Validating - at least one checkbox is checked

I have a problem in validating whether at least one checkbox is checked or not. 我在验证是否至少一个复选框处于选中状态时遇到问题。

The same code is being used for a different form and its working perfectly but I can't figure why it doesn't on this form. 相同的代码用于另一种形式,并且可以完美地工作,但是我无法弄清楚为什么它不在这种形式上。

Script: 脚本:

if(jQuery('#MOTForm input[type=checkbox]:checked').length == 0) { 
       alert("1");
       valid = valid && false;
       $("#MOTFORMERROR").css('color', 'red');
       $("#MOTFORMERROR").html("*Choose at least one");
}else{
       $("#MOTFORMERROR").html("");
}

Html: HTML:

<td style="width: 10%;" rowspan="3">
    <div style="padding-left:5px;">
       <form id="MOTForm">
           <input name="" type="checkbox"  class="form-check-input"/> HEMS<br />
           <input name="" type="checkbox"  class="form-check-input"/> EMS<br /> 
           <input name="" type="checkbox"  class="form-check-input"/> Walk-in<br />
       </form>

       <p id="MOTFORMERROR"></p>
    </div>
</td>

The code in the block of the if statement is being run all the time, instead of the code in the block of the else statement, even if one or all checkboxes are checked! if语句块中的代码正在运行的所有的时间,而不是在else语句块中的代码,即使一个或所有复选框被选中!

Since the variable valid wasn't defined, there was an error in your initial code (see below). 由于未定义有效变量,因此初始代码中存在错误(请参见下文)。 This error is visible in the browser console . 此错误在浏览器控制台中可见。

Uncaught ReferenceError: valid is not defined 未捕获的ReferenceError:有效未定义

Because of that error, the lines after valid = valid && false; 由于该错误, valid = valid && false;之后的行valid = valid && false; are not being executed. 没有被执行。

To fix this, declare that variable before this code is run: 要解决此问题,请在运行此代码之前声明该变量:

var valid = false;
//...other code to check if form is valid

Then move the original JavaScript code into a function that can be run on submit (eg function check() {...} ). 然后将原始JavaScript代码移到可以在Submit上运行的函数中(例如function check() {...} )。 See this demonstrated below. 请参阅下面演示的内容。 It uses the jQuery function .click() to bind the event handler to the submit button. 它使用jQuery函数.click()将事件处理程序绑定到提交按钮。 You will also notice it uses .ready() to wait until the DOM is ready before binding the event handler to the submit button. 您还将注意到它使用.ready()等待DOM准备就绪,然后再将事件处理程序绑定到Submit按钮。

 //wait until DOM is ready to bind check function to button click $(document).ready(function(readyEvent) { $('#submit').click(check); }) var valid = false; function check() { if (jQuery('#MOTForm input[type=checkbox]:checked').length == 0) { alert("1"); valid = valid && false; $("#MOTFORMERROR").css('color', 'red'); $("#MOTFORMERROR").html("*Choose at least one"); } else { console.log('no error- clearing error html'); $("#MOTFORMERROR").html(""); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div style="padding-left:5px;"> <form id="MOTForm"> <input name="" type="checkbox" class="form-check-input" /> HEMS <br /> <input name="" type="checkbox" class="form-check-input" /> EMS <br /> <input name="" type="checkbox" class="form-check-input" /> Walk-in <br /> <button id="submit"> Submit </button> </form> <p id="MOTFORMERROR"></p> </div> 

Update: 更新:

You typed a comment on your post (replying to questions in other comments): 您在帖子上输入了评论(回复其他评论中的问题):

valid is declared at the beginning of .click 在.click的开头声明有效

Now that that information is revealed, it makes me feel like most of what I said above is useless. 现在,这些信息被揭示了,这使我感到上面所说的大部分内容都是无用的。 Moving the declaration of valid into the click handler seems like a trivial change and there isn't much different besides that... See the example below: 有效声明移到点击处理程序中似乎是一个微不足道的更改,除此之外没有太大不同...请参见以下示例:

 //wait until DOM is ready to bind check function to button click $(document).ready(function(readyEvent) { $('#submit').click(check); }) function check() { var valid = false; if (jQuery('#MOTForm input[type=checkbox]:checked').length == 0) { alert("1"); valid = valid && false; $("#MOTFORMERROR").css('color', 'red'); $("#MOTFORMERROR").html("*Choose at least one"); } else { console.log('no error- clearing error html'); $("#MOTFORMERROR").html(""); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div style="padding-left:5px;"> <form id="MOTForm"> <input name="" type="checkbox" class="form-check-input" /> HEMS <br /> <input name="" type="checkbox" class="form-check-input" /> EMS <br /> <input name="" type="checkbox" class="form-check-input" /> Walk-in <br /> <button id="submit"> Submit </button> </form> <p id="MOTFORMERROR"></p> </div> 

your code does not show when the javascript is executed, maybe your checkboxes are not yet rendered when you look for them. 您的代码执行javascript 不会显示,可能当您寻找它们时,复选框尚未呈现。

In fact if you run your code in the exact order you posted here is perfectly normal that your condition is always true. 实际上,如果按照您在此处发布的确切顺序运行代码,这是完全正常的,则您的条件始终为真。

If you put your code inside a function to be called after all the HTML is rendered everything works perfectly: 如果将代码放在呈现所有HTML之后要调用的函数中,则一切将正常运行:

<td style="width: 10%;" rowspan="3">
    <div style="padding-left:5px;">
        <form id="MOTForm">
            <input name="" type="checkbox"  class="form-check-input"/> HEMS<br />
            <input name="" type="checkbox"  class="form-check-input"/> EMS<br />
            <input name="" type="checkbox"  class="form-check-input"/> Walk-in<br />
        </form>
        <p id="MOTFORMERROR"></p>
    </div>
</td>



<!-- ... -->



<button id="check_btn">Click me</button>



<!-- ... -->



<script>
var valid;

$('#check_btn').click(function() {
    if ($('#MOTForm input[type=checkbox]:checked').length == 0) {
        valid = false;
        $("#MOTFORMERROR").css('color', 'red');
        $("#MOTFORMERROR").html("*Choose at least one");
    } else {
        $("#MOTFORMERROR").html("");
    }
});
</script>

Please have a look at the following snippet. 请查看以下代码段。 It does that you are looking for. 它确实是您要找的。 I removed the valid variable, since it isn't apparent, where this parameter is used. 我删除了valid变量,因为它不明显,使用了此参数。 Apparently, you can add it and use it as you think. 显然,您可以按照自己的想法添加和使用它。

 $(function(){ function checkCheckBoxes(){ if($('#MOTForm input[type=checkbox]:checked').length == 0) { alert("1"); $("#MOTFORMERROR").css('color', 'red'); $("#MOTFORMERROR").html("*Choose at least one"); } else { $("#MOTFORMERROR").html(""); } } $(".js-check").on("change", checkCheckBoxes); checkCheckBoxes(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <td style="width: 10%;" rowspan="3"> <div style="padding-left:5px;"> <form id="MOTForm"> <input name="" type="checkbox" class="form-check-input js-check"/> HEMS<br /> <input name="" type="checkbox" class="form-check-input js-check"/> EMS<br /> <input name="" type="checkbox" class="form-check-input js-check"/> Walk-in<br /> </form> <p id="MOTFORMERROR"></p> </div> </td> 

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

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