Reputation: 25
We are calling a jQuery function using onclick on a checkbox. We want that checkbox to toggle all checkboxes below it. Here is the HTML for the toggle checkbox:
<input type="checkbox" id="toggle" name="toggle" class="daxle_cb" value="" onclick="daxleToggleCB('adminForm');" />
And here is the function:
function daxleToggleCB( formName )
{
jQuery('#' + formName).find('input[type=checkbox]').prop('checked', this.checked);
};
However, this is not working. What does work is this:
function daxleToggleCB( formName) {
jQuery( ':checkbox[name=toggle]' ).click
(
function ()
{
jQuery( '#'+formName ).find( 'input[type=checkbox]' ).prop( 'checked', this.checked );
}
);
};
Although, this function only works on the third click of the checkbox. So the problem is getting the checkboxes to toggle on the first click.
Upvotes: 0
Views: 9196
Reputation: 1224
$('input[type=checkbox]').click(function(event){
$(event.currentTarget).val($(event.currentTarget)[0].checked);
});
You can use event object to hander event on all checkboxes.Here is common and short way
Upvotes: 0
Reputation: 17481
You just need one click event to your checkbox. Also, you are adding the click event to all the checkboxs on your document, not only inside the form
. So, Rewrite your function:
function daxleToggleCB( formName) {
$('#'+formName+' input:checkbox').click(function(){
var $inputs = $('#'+formName+' input:checkbox');
if($(this).is(':checked')){ // <-- is current input checked?
$inputs.prop('checked',this.checked); // <-- check all
}
});
}
Then put this on your document to call the function:
$(document).ready(daxleToggleCB('myForm'));
Upvotes: 0
Reputation: 318342
<input type="checkbox" id="toggle" name="toggle" class="daxle_cb" value="" />
That looks like an ID ?
$('#toggle').on('change', function() {
$( this.form ).find('input[type="checkbox"]').prop('checked', this.checked);
})
Upvotes: 1
Reputation: 590
Your function is defining the click handler inside of the function called with the "onclick" attribute. Instead this should be inside of a Doc-On-Ready function to define the click handler when the page loads and not using the "onclick" attribute.
$(function(){
$( ':checkbox[name=toggle]' ).click
(
function ()
{
//Your Code Here
}
);
});
Upvotes: 0
Reputation: 1508
first, your not binding your jQuery.click() event until it's been clicked once at least.
then it looks like you have two events firing.
you have the inline onclick event, as well as the jQuery.click event.
Upvotes: 1