简体   繁体   English

使用Java复选框验证表单

[英]Validate form with checkboxes using Javascript

I have a set of checkboxes in a form as follows: 我有一组复选框,形式如下:

<form name="form1" onsubmit="return window.Validate()" method="post" action="myprog.cgi">
    <div id="filters"> 
        <input name="One_f" type="checkbox"> No. 1<br> 
        <input name="Two_f" type="checkbox"> No. 2<br> 
        <input name="Three_f" type="checkbox"> No. 3<br>
    </div>
    <div id="Colors">
        <input name="Red" type="checkbox"> Red<br> 
        <input name="Blue" type="checkbox"> Blue<br> 
        <input name="Green" type="checkbox"> Green<br>
    </div>
    <div id="Button">
        <input name="Submit" value="Submit" type="submit">
    </div>
</form> 

I want to write a function Validate in Javascript that would see whether any of the checkboxes in the div id filters is checked. 我想用Javascript编写一个Validate函数,该函数将查看是否已检查div id filters中的任何复选框。 If none of them is checked, it should show an alert box and prevent the cgi from getting executed. 如果未选中任何一个,它将显示一个警告框并阻止cgi被执行。 The checkboxes in the div filters all have their names ending in _f , if that helps. div filters所有复选框的名称都以_f结尾,如果有帮助的话。 How do I write such a function? 如何编写这样的功能?

Here's a jQuery solution, I'll add a plain JS one in a few moments. 这是一个jQuery解决方案,稍后我将添加一个普通的JS。

$('form[name="form1"]').on('submit', function(e) {
    if(!$('#filters input:checkbox:checked').length) {
        e.preventDefault();
        alert('Please select at least one filter.');
    }
});

This codes does not require the onsubmit inline event. 此代码不需要 onsubmit内事件。

Since you are not familiar with jQuery I'll explain it more thoroughly: 由于您不熟悉jQuery,因此我将对其进行更彻底的解释:

  • $('form[name="form1"]') creates a jQuery object containing all elements matching the selector. $('form[name="form1"]')创建一个jQuery对象,其中包含与选择器匹配的所有元素。 It would be faster if you gave your form id="form1" and used $('#form1') 如果您给表单id="form1"并使用$('#form1')会更快
  • .on() binds an event handler. .on()绑定事件处理程序。 The first argument passed to the callback function is a wrapped event object which we'll need to prevent the form from being submitted if necessary. 传递给回调函数的第一个参数是包装的事件对象,如果需要,我们将需要阻止该对象提交。
  • $('#filters input:checkbox:checked') selects all checked checkboxes that are children of #filters . $('#filters input:checkbox:checked')选择所有属于#filters子级的选中复选框。 :checkbox and :checked are pseudo-selectors which will only match checkboxes that are currently checked) :checkbox:checked是伪选择器,将仅与当前选中的复选框匹配)
  • .length is the number of elements in the jQuery object - if nothing is checked it's zero .length是jQuery对象中元素的数量-如果未选中则为零
  • e.preventDefault(); prevents the default action of the event from being executed, ie the form will not be submitted. 阻止执行事件的默认操作,即将不提交表单。

Usually you would wrap the whole code with $(document).ready(function() { ... }); 通常,您将使用$(document).ready(function() { ... });包装整个代码$(document).ready(function() { ... }); to make it execute as soon as the DOM is ready - if you put the <script> tag containing the code after the </form> tag of your form, it's not necessary though. 使其在DOM准备就绪后立即执行-如果将包含代码的<script>标记放在</form></form>标记之后,则没有必要。


If you really want a plain JS solution, try this: 如果您真的想要普通的JS解决方案,请尝试以下操作:

function Validate() {
    var container = document.getElementById('filters');
    var checked = 0;
    for(var i = 0; i < container.childNodes.length; i++) {
        var elem = container.childNodes[i];
        if(elem.tagName == 'INPUT' && elem.type == 'checkbox' && elem.checked) {
            checked++;
        }
    };
    if(checked) {
        return true;
    }
    alert('Please select at least one filter.');
    return false;
}

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

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