Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I have created a plugin where in I replace standard checkbox with iPhone like slide button. I'm able to bind the button with checkbox, i.e. when I click on YES button, checkbox is checked and when I click on NO button, checkbox is unchecked. Similarly I have created a plugin for radio button too. Now the problem is, if someone check the checkbox using jquery or select the radio button using jquery, how do I listen to this event and change corresponding button I have created using plugin, given that I don't have control over code which selects the radio button.

Sample code (I want change event to be called on click of button, given that I don't control click of button. Basically I want to listen to the event):

<input type="radio" name="radio" id="radio1"> Radio 1 </BR>
<input type="radio" name="radio" id="radio2"> Radio 2 </BR>
<input type="radio" name="radio" id="radio3"> Radio 3 </BR>
<button>click me</button>

$('input:radio').change(function(){
    alert($(this).attr('id') + ' is changed');
});

$('button').click(function(){
    $('#radio1').prop('checked', 'true');
});

http://jsfiddle.net/s24101984/v3Zfn/

share|improve this question
    
Pass a boolean true/false to prop instead of a string! – ThiefMaster Apr 7 '13 at 8:42

According to http://stackoverflow.com/a/4836831/280222 it's by design that JavaScript doesn't trigger the event when the check box is updated programatically.

If you have control over the code changing the attribute then you can use:

$('button').click(function(){
    $('#radio1').prop('checked', true).change();
});

In any case: If you're writing a plugin I suggest that you make it an implementation detail that use use a check box underneath the hood. Try to offer a suitable API for your users instead. That would also work this problem.

share|improve this answer
    
that's the issue @Anders Abel, I don't have control over this click event on button. I have to listen to the change in property of radio somehow :(. As I'm creating a plugin, I don't have control over actual code of application. Can you please elaborate on API part ? – Sandeep Choudhary Apr 7 '13 at 8:48

Ok I got the answer for this, here's the link where this has been answered LINK

We can use Hooks for this, sample:

jQuery.attrHooks.checked = {
    set: function (el, value) {
        el.checked = value;
        $(el).trigger('change');
    }
};

similarly we have propHooks, jsfiddle as shared in the link too

http://jsfiddle.net/2nKPY/

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.