Get checkbox status using javascript

Sasindu H picture Sasindu H · Jun 1, 2011 · Viewed 79.2k times · Source

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

Answer

Rudu picture Rudu · Jun 1, 2011

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