Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get checkbox status using javascript

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

like image 565
Sasindu H Avatar asked Jun 01 '11 16:06

Sasindu H


People also ask

How do you check checkbox is checked or not?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

Which method is used to check the status of checkbox?

prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.

What is the value of checkbox when checked?

The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.


2 Answers

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;
  }
}
like image 82
Rudu Avatar answered Oct 05 '22 22:10

Rudu


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
like image 34
karim79 Avatar answered Oct 05 '22 23:10

karim79