How can I check if a checkbox is checked?

前端 未结 14 1101
轮回少年
轮回少年 2020-11-22 14:28

I am building a mobile web app with jQuery Mobile and I want to check if a checkbox is checked. Here is my code.



        
相关标签:
14条回答
  • 2020-11-22 14:46

    This should work

        function validate() {
            if ($('#remeber').is(':checked')) {
                alert("checked");
            } else {
                alert("You didn't check it! Let me check it for you.");
            }
        }
    
    0 讨论(0)
  • 2020-11-22 14:47

    checked is boolean property so you can directly use it in IF condition:-

     <script type="text/javascript">
        function validate() {
            if (document.getElementById('remember').checked) {
                alert("checked");
            } else {
                alert("You didn't check it! Let me check it for you.");
            }
        }
        </script>
    
    0 讨论(0)
  • 2020-11-22 14:47

    Use this below simple code: https://jsfiddle.net/Divyesh_Patel/v7a4h3kr/7/

    <input type="checkbox" id="check">
    <a href="#" onclick="check()">click</a>
    <button onclick="check()">button</button>
    <script>
     function check() {
        		if (document.getElementById('check').checked) {
                alert("checked");
            } else {
                alert("Not checked.");
            }
           
        }
    
    </script>

    0 讨论(0)
  • 2020-11-22 14:47

    You can also use JQuery methods to accomplish this:

    <script type="text/javascript">
    if ($('#remember')[0].checked) 
    {
     alert("checked");
    }
    </script>
    
    0 讨论(0)
  • 2020-11-22 14:49

    I am using this and it works for me with Jquery:

    Jquery:

    var checkbox = $('[name="remember"]');
    
    if (checkbox.is(':checked'))
    {
        console.log('The checkbox is checked');
    }else
    {
        console.log('The checkbox is not checked');
    }
    

    Is very simple, but work's.

    Regards!

    0 讨论(0)
  • 2020-11-22 14:49

    Try This

    <script type="text/javascript">
    window.onload = function () {
        var input = document.querySelector('input[type=checkbox]');
    
        function check() {
            if (input.checked) {
                alert("checked");
            } else {
                alert("You didn't check it.");
            }
        }
        input.onchange = check;
        check();
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题