jQuery: Test if checkbox is NOT checked

前端 未结 18 921
太阳男子
太阳男子 2020-12-02 07:12

I\'m having trouble figuring this out. I have two checkboxes (in the future will have more):

  • checkSurfaceEnvironment-1
  • checkSurface
相关标签:
18条回答
  • 2020-12-02 07:58

    One reliable way I use is:

    if($("#checkSurfaceEnvironment-1").prop('checked') == true){
        //do something
    }
    

    If you want to iterate over checked elements use the parent element

    $("#parentId").find("checkbox").each(function(){
        if ($(this).prop('checked')==true){ 
            //do something
        }
    });
    

    More info:

    This works well because all checkboxes have a property checked which stores the actual state of the checkbox. If you wish you can inspect the page and try to check and uncheck a checkbox, and you will notice the attribute "checked" (if present) will remain the same. This attribute only represents the initial state of the checkbox, and not the current state. The current state is stored in the property checked of the dom element for that checkbox.

    See Properties and Attributes in HTML

    0 讨论(0)
  • 2020-12-02 07:58

    I used this and in worked for me!

    $("checkbox selector").click(function() {
        if($(this).prop('checked')==true){
           do what you need!
        }
    });
    
    0 讨论(0)
  • 2020-12-02 08:01
    if (!$("#checkSurfaceEnvironment-1").is(":checked")) {
        // do something if the checkbox is NOT checked
    }
    
    0 讨论(0)
  • 2020-12-02 08:06

    Here is the simplest way given

     <script type="text/javascript">
    
            $(document).ready(function () {
                $("#chk_selall").change("click", function () {
    
                    if (this.checked)
                    {
                        //do something
                    }
                    if (!this.checked)
                    {
                        //do something
    
                    }
    
                });
    
            });
    
        </script>
    
    0 讨论(0)
  • 2020-12-02 08:07

    Simple and easy to check or unchecked condition

    <input type="checkbox" id="ev-click" name="" value="" >
    
    <script>
        $( "#ev-click" ).click(function() {
            if(this.checked){
                alert('checked');
            }
            if(!this.checked){
                alert('Unchecked');
            }
        });
    </script>
    
    0 讨论(0)
  • 2020-12-02 08:07

    There are two way you can check condition.

    if ($("#checkSurfaceEnvironment-1").is(":checked")) {
        // Put your code here if checkbox is checked
    }
    

    OR you can use this one also

    if($("#checkSurfaceEnvironment-1").prop('checked') == true){
        // Put your code here if checkbox is checked
    }
    

    I hope this is useful for you.

    0 讨论(0)
提交回复
热议问题