Frank van Wensveen
Frank van Wensveen

Reputation: 562

Using jQuery to trigger actions on checking and unchecking a checkbox

There are several questions regarding jQuery and checkboxes with good answers and code snippets available on Stack Overflow, but apparently I have managed to misunderstand all of them.

I have the following HTML code in my form:

<input type="checkbox" name="copyAddress" id="copyAddress" value="1" />

Javascript code is as follows:

  $('#copyAddress').change(function () {
    $(this).attr('checked')
      ? alert ("Checked")
      : alert ("Unchecked");

According to this post the above should work. I have also tried using .trigger(), .click() etc. instead of .change(), and using if() rather than a logic operator as a conditional. In all cases the above Javascript code does get triggered, but regardless of the checked or unchecked status of the checkbox, I always get an "Unchecked" alert. In other words, triggering is not the issue here, it's the condition (the checked or unchecked status) of the checkbox that is not being detected (or handled) properly.

Obviously I'm overlooking something here. What is it?

Upvotes: 0

Views: 922

Answers (3)

Aditya Kresna Permana
Aditya Kresna Permana

Reputation: 12099

Hope this help

$('#copyAddress').on('change', function(){
    if(this.checked){
        // Do some action when checked
    }else{
        // Do some action when unchecked
    }
});

Upvotes: 0

Demosthenes
Demosthenes

Reputation: 364

Try this:

$("#copyAddress").change(function () { $(this).is(":checked") ? alert ("Checked") : alert ("Unchecked"); });

JSFiddle: http://jsfiddle.net/9MfLg/

Upvotes: 2

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

you can use prop() like this:

$('#copyAddress').change(function () {
    $(this).prop('checked')
      ? alert ("Checked")
      : alert ("Unchecked");
  });

FIDDLE EXAMPLE

or:

$('#copyAddress').change(function () {
    this.checked
      ? alert ("Checked")
      : alert ("Unchecked");
  });

FIDDLE DEMO

Upvotes: 1

Related Questions