Javascript 检查是否使用 jquery 检查输入

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

check if input is checked using jquery

javascriptjquery

提问by cmplieger

How would I achieve this:

我将如何实现这一目标:

if($(this).parent().find('input:checked') == true)

{$(this).find('.switch').attr('state','on');}
else{$(this).find('.switch').attr('state','off');}

I know this is wrong but you get the idea I think :). If there is an input that is checked add state on if not state off.

我知道这是错误的,但你明白我的想法:)。如果有一个被选中的输入,如果不是状态关闭,则添加状态。

回答by ezakto

Try with

试试

if($(this).parent().find('input').is(':checked')) {
    something();
}

This works if there's only one checkbox.

如果只有一个复选框,则此方法有效。

回答by Daff

It is not necessarily wrong, but the selector returns all elements that apply to the condition. Therefore you have to check if the length is not 0:

不一定是错误的,但选择器返回适用于条件的所有元素。因此,您必须检查长度是否不为 0:

if($(this).parent().find('input:checked').length)

回答by Ma Jerez

Supposign input[type=checkbox] = this, you can check it on the element itself.

假设input[type=checkbox] = this,您可以在元素本身上检查它。

Source: jQuery docs

来源:jQuery 文档

$("input[type=checkbox]").change(function(){
    if ( this.checked ){}
    //or
    if ( $(this).prop("checked") ){}   
    //or
    if ( $(this).is(":checked") ){}
});

回答by Code Buster

This also works if you know the id of the input html element:

如果您知道输入 html 元素的 id,这也适用:

if($('input#element_id_name:checked').length>0) {
  //your code here.
}

回答by Maya

If you know the ID, just use:

如果您知道 ID,只需使用:

if ($("#myCheckBox").is(":checked")) {  

}

回答by Stuart Burrows

Try doing this:

尝试这样做:

if ($(this).parent().find('input:checked').length > 0) {    
    $(this).find('.switch').attr('state','on');
} else {
    $(this).find('.switch').attr('state','off');
}

This assumes you have only 1 input within the scope of $(this).parent()

这假设您在范围内只有 1 个输入 $(this).parent()