How to check whether a checkbox is checked in jQue

2018-12-31 00:34发布

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.

For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.

But the following code returns false by default:

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

How do I successfully query the checked property?

30条回答
伤终究还是伤i
2楼-- · 2018-12-31 00:54

Use jQuery's is() function:

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else
    $("#txtAge").hide();  // unchecked
查看更多
若你有天会懂
3楼-- · 2018-12-31 00:55

You can use:

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

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

Both of them should work.

查看更多
无与为乐者.
4楼-- · 2018-12-31 00:56

There are many ways to check if a checkbox is checked or not:

Way to check using jQuery

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

Check example or also document:

查看更多
倾城一夜雪
5楼-- · 2018-12-31 00:56

Though you have proposed a JavaScript solution for your problem (displaying a textbox when a checkbox is checked), this problem could be solved just by css. With this approach, your form works for users who have disabled JavaScript.

Assuming that you have the following HTML:

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

You can use the following CSS to achieve the desired functionality:

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

For other scenarios, you may think of appropriate CSS selectors.

Here is a Fiddle to demonstrate this approach.

查看更多
伤终究还是伤i
6楼-- · 2018-12-31 00:58

Toggle: 0/1 or else

<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');
    };
});
查看更多
不再属于我。
7楼-- · 2018-12-31 00:58

I think it will be the simple one

$('#isAgeSelected').change(function() {
    if($(this).is(":checked")) {
        $('#txtAge').show();
    }
else{
        $('#txtAge').hide();
    }                                          
});
查看更多
登录 后发表回答