0

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?

1
  • use javascript this.checked or jQuery $(this).is(':checked') Commented Jun 30, 2014 at 17:19

3 Answers 3

2

Try this:

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Hope this help

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.