Adam Levitt
Adam Levitt

Reputation: 10476

Checkbox not being checked

Looking at this jsFiddle, my checkbox is never getting the checked attribute. This is a VERY simple test, and yet I cannot get the alert to show true.

http://jsfiddle.net/ZLpHv/

<input type="checkbox" id="checky" />

$(document).ready(function() {
    $("#checky").click(function() {
       alert($(this).is("checked")); 
    });
});

Why does the alert show false in both cases? And why does the checked attribute never get set onto the checkbox? What am I doing wrong here?

Upvotes: 0

Views: 532

Answers (4)

Nisarg
Nisarg

Reputation: 3282

$(function() {
   //checkbox
   $("#terms").click(function(){
       //if this...
       //alert("this")...
       if($("#terms").is(':checked'))
       {              
          alert("im checked");
       }
   });
   //button
   $("#buttonID").click(function(e){
       if(!$("#terms").is(':checked'))
       {
           alert("you did not check the agree to terms..."); 
           e.preventDefault();
       }
   });
 }

You can use this it works for me

Upvotes: 1

Michael Bialas
Michael Bialas

Reputation: 76

You forget the ":".

alert($(this).is(":checked"));

Upvotes: 2

insertusernamehere
insertusernamehere

Reputation: 23600

It's actually: alert($(this).is(":checked"));

Demo: http://jsfiddle.net/AdFEf/

Upvotes: 5

adeneo
adeneo

Reputation: 318342

It's actually :

$(this).is(":checked")

And binding the change event makes it work even if it's checked with the keyboard:

$(document).ready(function() {
    $("#checky").on('change', function() {
       alert($(this).is(":checked")); 
    });
});

Upvotes: 8

Related Questions