127

When I check a checkbox, I want it to turn <p> #0099ff.

When I uncheck the checkbox, I want it to undo that.

Code I have so far:

$('#checkbox').click(function(){
    if ($('#checkbox').attr('checked')) {
        /* NOT SURE WHAT TO DO HERE */
    }
}) 
John Slegers
  • 45,213
  • 22
  • 199
  • 169
android.nick
  • 11,069
  • 23
  • 77
  • 112
  • 1
    "... when it's unchecked, to disable that same function." - the function passed to `.click()` is invoked on the click event. Therefore I don't understand what you mean by "enable" and "disable". If the checkbox is checked you can invoke function `a()`. But you must write the reverse function to invoke when the checkbox is *not* checked. I'm confused. – jensgram Nov 22 '10 at 08:59
  • You can, of course, [`.bind()`](http://api.jquery.com/bind/) and [`.unbind()`](http://api.jquery.com/unbind/) events to *another* element based on the checkbox state. Is that what you're after? – jensgram Nov 22 '10 at 09:01
  • 1
    Sorry for spamming but I've made [an example](http://jsfiddle.net/jensgram/jW9jr/1/) of what I'm talking about. – jensgram Nov 22 '10 at 09:07
  • 1
    I know this is an old post, but now jQuery uses `prop()` for what this question wanted to use `attr()` for; the `prop()` method had not been created back then. The answers about `this.checked` are probably still useful, however. – trysis May 02 '14 at 00:51

11 Answers11

235

I would use .change() and this.checked:

$('#checkbox').change(function(){
    var c = this.checked ? '#f00' : '#09f';
    $('p').css('color', c);
});

--

On using this.checked
Andy E has done a great write-up on how we tend to overuse jQuery: Utilizing the awesome power of jQuery to access properties of an element. The article specifically treats the use of .attr("id") but in the case that #checkbox is an <input type="checkbox" /> element the issue is the same for $(...).attr('checked') (or even $(...).is(':checked')) vs. this.checked.

Community
  • 1
  • 1
jensgram
  • 31,109
  • 6
  • 81
  • 98
48

Try this.

$('#checkbox').click(function(){
    if (this.checked) {
        $('p').css('color', '#0099ff')
    }
}) 

Sometimes we overkill jquery. Many things can be achieved using jquery with plain javascript.

Chinmayee G
  • 7,947
  • 2
  • 31
  • 41
34

It may happen that "this.checked" is always "on". Therefore, I recommend:

$('#checkbox').change(function() {
  if ($(this).is(':checked')) {
    console.log('Checked');
  } else {
    console.log('Unchecked');
  }
});
Benny Code
  • 51,456
  • 28
  • 233
  • 198
21

it's better if you define a class with a different colour, then you switch the class

$('#checkbox').click(function(){
    var chk = $(this);
    $('p').toggleClass('selected', chk.attr('checked'));
}) 

in this way your code it's cleaner because you don't have to specify all css properties (let's say you want to add a border, a text style or other...) but you just switch a class

  • 4
    +1 for generic solution. There is no reason to do `$('#checkbox').attr('checked')`, however, if we know that `#checkbox` *is* a checkbox (if not, the ID is rather misleading). `this.checked` will do. – jensgram Nov 22 '10 at 08:30
  • @jensgram @fcalderan +1 Thanks for the tip! I had never seen toggleClass with switch. I'm deleting my post as it's useless. Sorry to be so picky, but I think this answer would be 100% perfect without '#checkbox' being selected twice: maybe use $(this) instead? Or jensgram's solution? – attack Nov 22 '10 at 08:54
  • @attack of course you can cache your element before using (see the code now). this.checked is even faster than $(..).attr('checked') –  Nov 22 '10 at 09:04
4

I found out a crazy solution for dealing with this issue of checkbox not checked or checked here is my algorithm... create a global variable lets say var check_holder

check_holder has 3 states

  1. undefined state
  2. 0 state
  3. 1 state

If the checkbox is clicked,

$(document).on("click","#check",function(){
    if(typeof(check_holder)=="undefined"){
          //this means that it is the first time and the check is going to be checked
          //do something
          check_holder=1; //indicates that the is checked,it is in checked state
    }
    else if(check_holder==1){
          //do something when the check is going to be unchecked
          check_holder=0; //it means that it is not checked,it is in unchecked state
    }
     else if(check_holder==0){
            //do something when the check is going to be checked
            check_holder=1;//indicates that it is in a checked state
     }
});

The code above can be used in many situation to find out if a checkbox has been checked or not checked. The concept behind it is to save the checkbox states in a variable, ie when it is on,off. i Hope the logic can be used to solve your problem.

zedecliff
  • 84
  • 4
  • 1
    The solution is indeed crazy but not in a good way. Yes global variables can help you solve a problem today but they will almost certainly become a problem for you tomorrow. Try to avoid them where possible, which is 99 % of the time. They make it impossible to reason about your code without worrying about the global state. One global variable might look innocent but quickly it becomes tens then hundreds. Been there, seen that and it's not pretty. – bijancn Apr 17 '16 at 18:40
3

Check this code:

<!-- script to check whether checkbox checked or not using prop function -->
<script>
$('#change_password').click(function(){
    if($(this).prop("checked") == true){ //can also use $(this).prop("checked") which will return a boolean.
        alert("checked");
    }
    else if($(this).prop("checked") == false){
        alert("Checkbox is unchecked.");
    }
});
</script>
Si8
  • 9,141
  • 22
  • 109
  • 221
1

Probably you can go with this code to take actions as the checkbox is checked or unchecked.

$('#chk').on('click',function(){
    if(this.checked==true){
      alert('yes');
    }else{
      alert('no');
    }
});
Tunaki
  • 132,869
  • 46
  • 340
  • 423
1
$('#checkbox').change(function(){
   (this.checked)?$('p').css('color','#0099ff'):$('p').css('color','another_color');
});
1

I would do :

$('#checkbox').on("change", function (e){ 

    if(this.checked){

      // Do one thing 

    }

    else{

     // Do some other thing

    }

});

See : https://www.w3schools.com/jsref/prop_checkbox_checked.asp

Jon Ryan
  • 1,497
  • 1
  • 13
  • 29
0

Optimal implementation

$('#checkbox').on('change', function(){
    $('p').css('color', this.checked ? '#09f' : '');
});

Demo

$('#checkbox').on('change', function(){
    $('p').css('color', this.checked ? '#09f' : '');
});
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input id="checkbox" type="checkbox" /> 
<p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
    eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<p>
    Ut enim ad minim veniam, quis nostrud exercitation ullamco
    laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu
    fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est
    laborum.
</p>
John Slegers
  • 45,213
  • 22
  • 199
  • 169
0

Why not use the built in events?

$('#checkbox').click(function(e){
    if(e.target.checked) {
     // code to run if checked
        console.log('Checked');

     } else {

     //code to run if unchecked
        console.log('Unchecked');
     }
});
Paul 501
  • 707
  • 7
  • 14