Get checkbox status using javascript

廉价感情. 提交于 2019-12-18 21:04:18

问题


This is my checkbox HTML code

<input id="termsCheckbox" name="termsCheckbox" type="checkbox" value="terms" <?PHP echo $terms; ?> class="checkbox">

this is javascript code

var terms = $("#termsCheckbox");

function validateTerms(){
if(termsCheckbox.checked == false){
terms_div.addClass("terms_error");
return false;
}
else{           
terms_div.removeClass("terms_error");
return true;
}
}

I want to check whether checkbox checked or not and if not add a class to terms_div. Please help me to solve this problem. thanks


回答1:


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;
  }
}



回答2:


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



回答3:


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;
    }
}



回答4:


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




回答5:


if(document.form.termsCheckbox.checked==true)
alert('check box is cheked')


来源:https://stackoverflow.com/questions/6204885/get-checkbox-status-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!