Reputation: 1
I'm rewriting a plugin of mine and I want to try to take care of an issue we had in the past.
When you check the checkbox by clicking on it, the change event is triggered. It's being logged in the console.
However, if you use the button to the left of it, 'change' is not triggered.
With the plugin, I want to be able to detect this change if the user is checking the checkbox or radio button dynamically with code they already have.
Any thoughts?
HTML:
<input type="button" name="check" value="Checkbox" />
<input type="checkbox" name="newsletter" value="true" />
jQuery:
$(function() {
// This toggle checks and unckecks the box
$('input:button').toggle(function() {
$('input:checkbox').prop("checked", true);
}, function() {
$('input:checkbox').prop("checked", false);
});
// Detects change of checkbox
$('input:checkbox').on("change", function() {
console.log('checked!');
});
});
Upvotes: 0
Views: 1089
Reputation: 2858
Yep trigger the check box, I'd do it this way (replacing the first part of the code in your fiddle):
// This toggle checks and unckecks the box
$('input:button').on('click', function(event){
$('input:checkbox').trigger('click');
});
Assuming of course that your goal is to basically make the button the way in which you check or uncheck the box.
Upvotes: 0
Reputation: 415
$('input:button').click(function(){
$('input:checkbox').trigger("change");
});
this allows the "change" event to be triggered when you click on the button
Upvotes: 0
Reputation: 77956
Easiest fix is to fire the change event manually:
$('input:checkbox').prop("checked", true).change();
Edit: You can also simplify your button code instead of using toggle
, just use a click
and assign the checked
property to the opposite of its current value:
$('input:button').on('click',function() {
var $checkbox = $('input:checkbox');
$checkbox.prop('checked', !$checkbox.is(':checked')).change();
});
Upvotes: 1
Reputation: 38079
You could just fire the click event on the checkbox, instead of changing the property manually:
$('input:checkbox').click();
Upvotes: 0