如何检查jQuery中是否选中了复选框?

问题描述 投票:4250回答:61

我需要检查复选框的checked属性,并使用jQuery基于checked属性执行操作。

例如,如果选中年龄复选框,则需要显示一个文本框以输入年龄,否则隐藏文本框。

但是以下代码默认返回false

if ($('#isAgeSelected').attr('checked'))
{
    $("#txtAge").show();
}
else
{
    $("#txtAge").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" id="isAgeSelected"/>

<div id="txtAge" style="display:none">
Age is selected
</div>

如何成功查询checked属性?

jquery html dom checkbox
61个回答
3291
投票

如何成功查询已检查的属性?

复选框DOM元素的checked属性将为您提供元素的checked状态。

鉴于您现有的代码,您可以这样做:

if(document.getElementById('isAgeSelected').checked) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

但是,使用toggle有一个更漂亮的方法:

$('#isAgeSelected').click(function() {
    $("#txtAge").toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>

58
投票

对于checkbox属性使用Click事件处理程序是不可靠的,因为checked属性可以在事件处理程序本身的执行期间更改!

理想情况下,您希望将代码放入change事件处理程序中,例如每次更改复选框的值时都会触发它(与其执行方式无关)。

$('#isAgeSelected').bind('change', function () {

   if ($(this).is(':checked'))
     $("#txtAge").show();
   else
     $("#txtAge").hide();
});

55
投票

使用:

<input type="checkbox" id="abc" value="UDB">UDB
<input type="checkbox" id="abc" value="Prasad">Prasad
$('input#abc').click(function(){
  if($(this).is(':checked'))
  {
    var checkedOne=$(this).val()
    alert(checkedOne);

    // Do some other action
  }
})

如果您希望只有在取消选中时才需要执行必要的操作,这可能会有所帮助。


51
投票

我决定在没有jQuery的情况下发布关于如何做同样事情的答案。仅仅因为我是反叛者。

var ageCheckbox = document.getElementById('isAgeSelected');
var ageInput = document.getElementById('txtAge');

// Just because of IE <333
ageCheckbox.onchange = function() {
    // Check if the checkbox is checked, and show/hide the text field.
    ageInput.hidden = this.checked ? false : true;
};

首先,您可以通过ID获取这两个元素。然后为复选框的onchange事件分配一个函数,该函数检查复选框是否已被选中并正确设置age文本字段的hidden属性。在该示例中使用三元运算符。

这是一个fiddle供您测试。

附录

如果跨浏览器兼容性是一个问题,那么我建议将CSS display属性设置为none和inline。

elem.style.display = this.checked ? 'inline' : 'none';

较慢但跨浏览器兼容。


46
投票

我相信你可以这样做:

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}

43
投票

我遇到了完全相同的问题。我有一个ASP.NET复选框

<asp:CheckBox ID="chkBox1" CssClass='cssChkBox1' runat="server" />

在jQuery代码中,我使用以下选择器来检查是否选中了复选框,它似乎像魅力一样工作。

if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

我相信你也可以使用ID而不是CssClass,

if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

我希望这可以帮助你。


43
投票

有很多方法可以检查是否选中了复选框:

使用jQuery检查的方法

if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))

检查示例或文档:


41
投票

这是做同样事情的一些不同方法:

$(document).ready(function (){

    $('#isAgeSelected').click(function() {
        // $("#txtAge").toggle(this.checked);

        // Using a pure CSS selector
        if ($(this.checked)) {
            alert('on check 1');
        };

        // Using jQuery's is() method
        if ($(this).is(':checked')) {
            alert('on checked 2');
        };

        //  // Using jQuery's filter() method
        if ($(this).filter(':checked')) {
            alert('on checked 3');
        };
    });
});
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>

39
投票

这对我有用:

/* isAgeSelected being id for checkbox */

$("#isAgeSelected").click(function(){
  $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});

35
投票

用这个:

if ($('input[name="salary_in.Basic"]:checked').length > 0)

如果选中该复选框,则长度大于零。


34
投票

您可以使用此代码:

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});

1710
投票

使用jQuery的is()函数:

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else
    $("#txtAge").hide();  // unchecked

32
投票

我这样做的方法是:

if ( $("#checkbox:checked").length ) {       
    alert("checkbox is checked");
} else {
    alert("checkbox is not checked");
}

31
投票
$(selector).attr('checked') !== undefined

如果输入被检查,则返回true,如果不是,则返回false


30
投票
$(document).ready(function() {    
    $('#agecheckbox').click(function() {
        if($(this).is(":checked"))
        {
            $('#agetextbox').show();
        } else {
            $('#agetextbox').hide();
        }
    });
});

30
投票

您可以使用:

  if(document.getElementById('isAgeSelected').checked)
    $("#txtAge").show();  
  else
    $("#txtAge").hide();

if($("#isAgeSelected").is(':checked'))
  $("#txtAge").show();  
else
  $("#txtAge").hide();

他们两个都应该工作。


26
投票

1)如果您的HTML标记是:

<input type="checkbox"  />

attr使用:

$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set

如果使用道具:

$(element).prop("checked"); // Will give you false whether or not initial value is set

2)如果你的HTML标记是:

 <input type="checkbox"  checked="checked" />// May be like this also  checked="true"

attr使用:

$(element).attr("checked") // Will return checked whether it is checked="true"

使用的道具:

$(element).prop("checked") // Will return true whether checked="checked"

24
投票

此示例适用于按钮。

请尝试以下方法:

<input type="button" class="check" id="checkall" value="Check All" />  &nbsp; <input type="button" id="remove" value="Delete" /> <br/>

<input type="checkbox" class="cb-element"  value="1" /> Checkbox  1 <br/>
<input type="checkbox" class="cb-element"  value="2" /> Checkbox  2 <br/>
<input type="checkbox" class="cb-element"  value="3" /> Checkbox  3 <br/>


$('#remove').attr('disabled', 'disabled'); 

$(document).ready(function() {  

    $('.cb-element').click(function() {

        if($(this).prop('checked'))
        {
            $('#remove').attr('disabled', false);
        }
        else
        {
            $('#remove').attr('disabled', true);
        }
    });   

    $('.check:button').click(function()
{
    var checked = !$(this).data('checked');
    $('input:checkbox').prop('checked', checked);
    $(this).data('checked', checked);

    if(checked == true)
    {
        $(this).val('Uncheck All');
         $('#remove').attr('disabled', false);
    }

    else if(checked == false)
    {
        $(this).val('Check All');
        $('#remove').attr('disabled', true);
    }
});
});

24
投票

最佳答案并没有为我做到。这确实如此:

<script type="text/javascript">
    $(document).ready(function(){

        $("#li_13").click(function(){
            if($("#agree").attr('checked')){
                $("#saveForm").fadeIn();
            }
            else
            {
                $("#saveForm").fadeOut();
            }
        });
    });
</script>

基本上,当单击元素#li_13时,它会检查是否使用.attr('checked')函数检查元素#agree(这是复选框)。如果它是fadeIn #saveForm元素,如果不是fadeOut saveForm元素。


22
投票

我用这个:

 <input type="checkbox" id="isAgeSelected" value="1" /> <br/>
 <input type="textbox" id="txtAge" />

 $("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();

22
投票

虽然你已经为你的问题提出了一个JavaScript解决方案(当textboxcheckbox时显示checked),这个问题可以通过css解决。使用此方法,您的表单适用于已禁用JavaScript的用户。

假设您有以下HTML:

<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />

您可以使用以下CSS来实现所需的功能:

 #show_textbox:not(:checked) + input[type=text] {display:none;}

对于其他场景,您可能会想到适当的CSS选择器。

Here is a Fiddle to demonstrate this approach


21
投票

切换:0/1否则

<input type="checkbox" id="nolunch" />
<input id="checklunch />"

    $('#nolunch').change(function () {
    if ($(this).is(':checked')) {
        $('#checklunch').val('1');
    };
    if ($(this).is(':checked') == false) {
        $('#checklunch').val('0');
    };
});

521
投票

使用jQuery> 1.6

<input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />

// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true

使用新属性方法:

if($('#checkMeOut').prop('checked')) {
    // something when checked
} else {
    // something else when not
}

18
投票

我认为这将是一个简单的

$('#isAgeSelected').change(function() {
    if($(this).is(":checked")) {
        $('#txtAge').show();
    }
else{
        $('#txtAge').hide();
    }                                          
});

212
投票

jQuery 1.6+

$('#isAgeSelected').prop('checked')

jQuery 1.5及以下版本

$('#isAgeSelected').attr('checked')

任何版本的jQuery

// Assuming an event handler on a checkbox
if (this.checked)

所有功劳都归功于Xian


157
投票

我正在使用这个,这是完全正常的:

$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");

注意:如果选中该复选框,则返回true,否则为undefined,因此最好检查“TRUE”值。


140
投票

使用:

<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

$("#planned_checked").change(function() {
    if($(this).prop('checked')) {
        alert("Checked Box Selected");
    } else {
        alert("Checked Box deselect");
    }
});

    $("#planned_checked").change(function() {
        if($(this).prop('checked')) {
            alert("Checked Box Selected");
        } else {
            alert("Checked Box deselect");
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

114
投票

从jQuery 1.6开始,jQuery.attr()的行为发生了变化,鼓励用户不要使用它来检索元素的检查状态。相反,你应该使用jQuery.prop()

$("#txtAge").toggle(
    $("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
                                        // Return value changes with checkbox state
);

另外两种可能性是:

$("#txtAge").get(0).checked
$("#txtAge").is(":checked")

92
投票

这对我有用:

$get("isAgeSelected ").checked == true

其中isAgeSelected是控件的id。

此外,@ karim79的answer工作正常。我不确定在我测试时我错过了什么。

注意,这是答案使用Microsoft Ajax,而不是jQuery


84
投票

如果您使用的是jquery的更新版本,则必须使用.prop方法来解决您的问题:

如果选中,$('#isAgeSelected').prop('checked')将返回true,如果未选中则返回false。我确认了,我之前遇到过这个问题。 $('#isAgeSelected').attr('checked')$('#isAgeSelected').is('checked')正在返回undefined,这不是一个值得回答的情况。如下所示。

if($('#isAgeSelected').prop('checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

希望它有所帮助:) - 谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.