javascript 仅在至少选中一个复选框时提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22557055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:21:16  来源:igfitidea点击:

Submit form only if at least one checkbox is checked

javascriptjquerycheckboxsubmit

提问by user2132234

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>

回答by Arun P Johny

//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();
        }
    })
})

回答by Milind Anantwar

You can use :checkedselector along with .lengthto find checked checkbox count:

您可以使用:checked选择器和.length查找选中的复选框计数:

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

Demo

演示

回答by Yasser Shaikh

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

:检查选择将匹配检查或选择的所有元素。

You could try this

你可以试试这个

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

回答by Tuhin

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

我建议您使用“按钮”而不是“提交”。

please follow this

请按照这个

HTML->

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

         });
    });

回答by Paul S.

Vanilla JavaScriptequivalent of the jQueryway, using document.querySelector

Vanilla JavaScript等效于jQuery方式,使用document.querySelector

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

Demo

演示

回答by Jonathan Wommack

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.

最简单的方法是使用 javascript,幸运的是有人已经在这里完成了所有工作(使用 jQuery)。要适应该示例,您所需要做的就是将#form_check 更改为#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.

本质上,该示例正在做的是在看到正在尝试表单的提交操作之前强制自己然后它在表单元素内搜索具有选中状态的任何复选框元素,如果找不到任何则发送一个 preventdefault停止客户端/浏览器对提交操作请求的默认响应,否则只是正常发送。

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

另外关于其他答案,使用 === 更安全,返回 false 会给你一些冗余。这里有一些关于 return false 添加的内容的讨论。

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

此外,不要为此使用 click() ,因为您可能会遇到这样的用例,即您在技术上提交表单但实际上并未单击它,例如当您按下 Enter 键时

回答by G Ravinder

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