简体   繁体   中英

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. If none of them is checked, it should show an alert box and prevent the cgi from getting executed. The checkboxes in the div filters all have their names ending in _f , if that helps. How do I write such a function?

Here's a jQuery solution, I'll add a plain JS one in a few moments.

$('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.

Since you are not familiar with jQuery I'll explain it more thoroughly:

  • $('form[name="form1"]') creates a jQuery object containing all elements matching the selector. It would be faster if you gave your form id="form1" and used $('#form1')
  • .on() binds an event handler. 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 . :checkbox and :checked are pseudo-selectors which will only match checkboxes that are currently checked)
  • .length is the number of elements in the jQuery object - if nothing is checked it's zero
  • 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() { ... }); 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.


If you really want a plain JS solution, try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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