0

Please find the code below

$("#chkCopy").toggle(function () {
   copyDetails(); 
},
function () {
   emptyCopyDetails();
});

// functions which do not have any effect on the checkbox
function copyDetails() {

}

function emptyCopyDetails() {
}

The issue is that checkbox is not showing the checked state.

Demo

Thanks in advance

4 Answers 4

3

The .toggle() interrupts the check, since .toggle() actually calls e.preventDefault() on the click event underneath. Instead of that approach, I'd recommend something like this instead:

$("#chkCopy").change(function () {
  if(this.checked) {
    copyDetails();
  } else {
    emptyCopyDetails();
  }
});

Here's an updated/working version of your demo with the above approach.

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

Comments

2
$("#chkCopy").change(function () {                alert("1");

            },
            function () {
                alert("2");
            });

use change instead of toggle

3 Comments

This won't work, .change() doesn't have an overload with 2 handlers.
@Nick you can also use .click()
no...it also doesn't accept 2 handlers, .toggle() is a special function :)
1

From the documentation:

Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.

So you can't use toggle() if you want the check box to be checked and unchecked. You can use click() instead:

$("#chkCopy").click(function() {
   if (this.checked) {
       copyDetails();
   } else {
       emptyCopyDetails();
   }
});

Comments

0

take a look at this answer you would accomplish the same thing

Jquery toggle event is messing with checkbox value

1 Comment

That answer is a bad example of what to do as well, since this.checked is a directly accessible DOM property, $(this).attr("checked") is tremendous overkill.

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.