How do I check whether a checkbox is checked in jQuery?

前端 未结 30 3429
花落未央
花落未央 2020-11-21 04:44

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

30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 05:02

    How do I successfully query the checked property?

    The checked property of a checkbox DOM element will give you the checked state of the element.

    Given your existing code, you could therefore do this:

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

    However, there's a much prettier way to do this, using toggle:

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

提交回复
热议问题