15

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

Sasindu H
  • 1,538
  • 7
  • 24
  • 43

5 Answers5

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;
  }
}
Rudu
  • 15,682
  • 4
  • 47
  • 63
  • heh ours are really close. Only caveat on yours is if there happens to be any other classes assigned to the element itll wipe them out. – Loktar Jun 01 '11 at 17:10
  • I make only one change to this code `d.className='terms_error'; ` otherwise when i double press the submit button another 'terms_error' will add. thanks – Sasindu H Jun 01 '11 at 17:25
  • in this case no any other class in this element. But += will add same class twice. – Sasindu H Jun 01 '11 at 17:33
  • Good point Sassi, the `+=` should have be `=` although a double click should get a check/uncheck so className shouldn't get messed up (appended once, then cleared). – Rudu Jun 02 '11 at 17:53
2
if(document.form.termsCheckbox.checked==true)
alert('check box is cheked')
zod
  • 12,092
  • 24
  • 70
  • 106
1

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
karim79
  • 339,989
  • 67
  • 413
  • 406
1

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;
    }
}
Loktar
  • 34,764
  • 7
  • 90
  • 104
0

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

cusimar9
  • 5,185
  • 4
  • 24
  • 30