javascript 如果选中则显示提交按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16209679/
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 03:42:57  来源:igfitidea点击:

Show submit button if checked

javascriptjqueryhtmlcheckbox

提问by Stefan Frederiksen

I need to hide the submit button if none checkboxes is checked. if at least one is checked the submit button should be displayed. I use JQuery.

如果没有选中任何复选框,我需要隐藏提交按钮。如果至少选中一项,则应显示提交按钮。我使用 JQuery。

<input type="checkbox" name="prog" value="1">
<input type="checkbox" name="prog" value="2">

<input type="submit" id="submit_prog" value='Submit' />

EDIT

编辑

How can I combine it with a "check all" checkbox?

如何将其与“全部选中”复选框结合使用?

回答by nnnnnn

$(document).ready(function() {

    var $submit = $("#submit_prog").hide(),
        $cbs = $('input[name="prog"]').click(function() {
            $submit.toggle( $cbs.is(":checked") );
        });

});

Demo: http://jsfiddle.net/QMtey/1/

演示:http: //jsfiddle.net/QMtey/1/

The .toggle()methodaccepts a boolean for whether to show or hide.

.toggle()方法接受一个布尔值是显示还是隐藏。

回答by Greg Guida

I'll do you one better! You can do this with just css.

我给你做一个更好的!你可以只用 css 来做到这一点。

input[type=submit] {
  display:none;
}

input[type=checkbox]:checked ~ input[type=submit] {
  display:block;
}

Heres a demo: http://jsfiddle.net/5wASK/

这是一个演示:http: //jsfiddle.net/5wASK/

回答by Hilmi

with the following code when the user check some the button will appear and when uncheck all it will hide again.

使用以下代码,当用户选中某些按钮时,按钮将出现,取消选中所有按钮时,它将再次隐藏。

jQuery('[name="prog"]').click(function(){
    if (jQuery('[name="prog"]:checked').length > 0)    
        jQuery('#submit_prog').show();
    else jQuery('#submit_prog').hide();
});

回答by Mike

var $checkboxes = $('input[type=checkbox]');

$checkboxes.on('change', function() {
   $('#submit_prog').prop('disabled', !($checkboxes.length == $checkboxes.filter(':checked').length));
});

The idea is that you JavaScript to check if the amount of checkboxes matches the amount of checked checkboxes. The ! flips it and sets the submit button's disabled property.

这个想法是你 JavaScript 来检查复选框的数量是否与选中的复选框数量匹配。这 !翻转它并设置提交按钮的禁用属性。

回答by Frederik.L

$('input[name="prog"]').change(function(){
    var submitBtn=$('#submit_prog');
    if ($('input[name="prog"]:checked').length > 0) {
        submitBtn.show();
    } else {
        submitBtn.hide();
    }
});

回答by Sai Prasad Sabeson

Use toggle to hide and show the element.

使用切换来隐藏和显示元素。

$("input[name='prog']").on("change",function(){
        $("#submit_prog").toggle();
});