简体   繁体   中英

Submit form only if at least one checkbox is checked

i'm triyng to validate a form. In this form you've to choose at least one element by checkboxes, and I can't be sure about their quantity (it depends by elements number). I need to enable the submit input if one or more checkboxes are checked, and disable it if there aren't any checkbox checked, how can I do? Here's my code:

<form id="booking">
<input type="checkbox" name="room1" class="roomselect"/>
<input type="checkbox" name="room2" class="roomselect"/>
<input type="checkbox" name="room3" class="roomselect"/>
<input type="submit" value="Request" id="subm" />
</form>
//dom ready handler
jQuery(function ($) {
    //form submit handler
    $('#booking').submit(function (e) {
        //check atleat 1 checkbox is checked
        if (!$('.roomselect').is(':checked')) {
            //prevent the default form submit if it is not checked
            e.preventDefault();
        }
    })
})

You can use :checked selector along with .length to find checked checkbox count:

var len = $(".roomselect:checked").length;
if(len>0){
    //more than one checkbox is checked
 }

Demo

The :checked selector will Match all elements that are checked or selected.

You could try this

$("#subm").click(function(e){
        if($(".roomselect:checked").length == 0){
            e.preventDefault();
        }
    });

i suggest you to use "button" instead of "submit".

please follow this

HTML->

<form id="booking" action="https://www.google.co.in/search">
      <input type="checkbox" value="facebook" name="q"/>
       <input type="checkbox" value="gmail" name="q"/>
       <input type="checkbox" value="stackoverflow" name="q"/>
<input type="button" value="Request" id="submit" />

$(function(){

$("#submit").click(function(e){

    var number_of_checked_checkbox= $("input[name=q]:checked").length;
    if(number_of_checked_checkbox==0){
        alert("select any one");
    }else{
        $("#booking").submit();
    }

         });
    });

Vanilla JavaScript equivalent of the jQuery way, using document.querySelector

if (document.querySelector('.roomselect:checked')) {
    // somethings checked
}

Demo

The easiest method would be with javascript, fortunately someone's already done all the work here (with jQuery). All you'd need to do to adapt that example is to change #form_check to #booking.

Essentially what that example is doing is forcing itself before the submit action when it sees one is being tried for the form then it's searching inside the form element for any checkbox elements with a checked state and if it can't find any is sending a preventdefault to stop whatever the client/browser's default response to a submit action request would be or otherwise just sending as normal.

Also regarding the other answers, using === is more secure and returning false gives you some redundancy. Here's some discussion on what the return false adds.

Additionally don't use click() for this as you potentially run into use cases where you're technically submitting the form but aren't actually clicking it, like say when you hit enter

try this

var checked = false;
$(function(){
    $('#subm').click(function(e){
        checkall();
        if(!checked){
            e.preventDefault();
        }
    });
    $('.roomselect').change(function(e){
        checkall();
    });
    checkall();
});
function checkall()
{
    checked = $('.roomselect:checked').length > 0;
    $('#subm').prop('disabled',!checked);
}
$("#form_id").submit(function(e) {        
    var totalChecked = $('#div_id:input[type="checkbox"]:checked').length;        
    if(totalChecked < 1)
    {            
        alert('Please select at least one checkbox before submit');
        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