3

I'm building a jQuery plugin to style checkboxes. I hide the real one and after it insert button which when clicked toggles the hidden checkbox. But if I check the hidden checkbox via JavaScript, fake button doesn't change of course. I thought about making it to change using jQuery's .change() but it also doesn't trigger the change when made by JavaScript and not by actually clicking the checkbox.

I want plugin to be universal and to also work if someone has a button like "check all" or "uncheck all" which does the thing with JavaScript, I want my fake checkbox-buttons to change accordingly.

The question is what method should I use instead jQuery's change() in order to watch not only changes made by mouse clicks, but also by javascript for example $('checkbox').prop('checked', true);

edit2: I realized there is no proper way to watch properties with JavaScript, except checking the property several times a second for each checkbox which is very unattractive.I decided not to include such inefficient feature to my plugin and instead leave it to user to also trigger the change if he wants to manipulate values via JavaScript.

0

2 Answers 2

6

You can't watch properties. You could set up a timer that looks for changes every few milliseconds, but that is not satisfying.

Instead, you should rely on all other code to trigger the change event, when they want plugins like yours to update (there may also be cases when they don't):

$(':checkbox').prop('checked', true).change();
Sign up to request clarification or add additional context in comments.

Comments

0

You need to trigger the change event manually.

$('#checkbox').attr('checked', 'checked').change();

Have a look at this : JsFiddle

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.