How can I check if a checkbox is checked?

前端 未结 14 1099
轮回少年
轮回少年 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:30

    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("You didn't check it! Let me check it for you.");
            }
           
        }
    
    </script>

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

    If you are using this form for mobile app then you may use the required attribute html5. you dont want to use any java script validation for this. It should work

    <input id="remember" name="remember" type="checkbox" required="required" />
    
    0 讨论(0)
  • Try this:

    function validate() {
      var remember = document.getElementById("remember");
      if (remember.checked) {
        alert("checked");
      } else {
        alert("You didn't check it! Let me check it for you.");
      }
    }
    

    Your script doesn't know what the variable remember is. You need to get the element first using getElementById().

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

    You can try this:

    if ($(#remember).is(':checked')){
       alert('checked');
    }else{
       alert('not checked')
    }
    
    0 讨论(0)
  • 2020-11-22 14:39

    This should allow you to check if element with id='remember' is 'checked'

    if (document.getElementById('remember').is(':checked')
    
    0 讨论(0)
  • 2020-11-22 14:45

    remember is undefined … and the checked property is a boolean not a number.

    function validate(){
        var remember = document.getElementById('remember');
        if (remember.checked){
            alert("checked") ;
        }else{
            alert("You didn't check it! Let me check it for you.")
        }
    }
    
    0 讨论(0)
提交回复
热议问题