Get checkbox status using javascript

前端 未结 5 1427
时光说笑
时光说笑 2021-01-02 05:40

This is my checkbox HTML code

 class=\"che         


        
相关标签:
5条回答
  • 2021-01-02 06:01

    try adding onclick="validateTerms();" on the checkbox tag

    0 讨论(0)
  • 2021-01-02 06:02

    Live Demo (Click the "Terms Div" text to test)

    I didnt see the question tagged with jQuery, but I noticed a jQery selector was used.. so just to be safe I did it with pure JS anyway.

    Pure JS

    var terms = document.getElementById("termsCheckbox"),
        terms_div = document.getElementById("terms_div");
    
    function validateTerms(){
        if(terms.checked == false){
            if(terms_div.className.indexOf("terms_error")<0){
                terms_div.className += " terms_error";
            }
            return false;
        }else{      
            terms_div.className = terms_div.className.replace(/\bterms_error\b/,'');
            return true;
        }
    }
    
    0 讨论(0)
  • 2021-01-02 06:20

    You need to access the className variable (pure JS) the following assumes your div has an ID of terms_div, that terms_error is the only class you might want on the div, and that you setup your checkbox with onClick="validateTerms();"

    function validateTerms(){
      var c=document.getElementById('termsCheckbox');
      var d=document.getElementById('terms_div');
      if (c.checked) {
        d.className='';
        return true;
      } else { 
        d.className='terms_error';
        return false;
      }
    }
    
    0 讨论(0)
  • 2021-01-02 06:21

    Simply bind an onchange handler to your checkbox.

    $("#termsCheckbox").change(function() {
    
        // class will be removed if checked="checked"
        // otherwise will be added
        $(this).toggleClass("terms_error", !this.checked);
    }).change(); // set initial state
    
    0 讨论(0)
  • 2021-01-02 06:24
    if(document.form.termsCheckbox.checked==true)
    alert('check box is cheked')
    
    0 讨论(0)
提交回复
热议问题