I am trying to select all checkboxes on a page once the \'select all\' checkbox is clicked and i am using jquery for this as you can see at the below link:
http://js
Your fiddle works after I made 3 fixes :
isChecked
functionattr
to check the boxes$(document).ready(function () {
$('#selectall').click(function () {
$('.selectedId').prop('checked', $(this).is(":checked"));
});
});
more Optimized
Assume parent checkbox has a class of mainselect and all child have class of childselect
Then selecting parent will select all checkbox and vice-versa with the code below:
$('#mainselect').live('change',function(){
if($(this).attr('checked') == 'checked') {
$('.childselect').attr('checked','checked');
} else {
$('.childselect').removeAttr('checked');
}
});
This should do the trick for you.
$(document).ready(function () {
$('#selectall').click(function () {
var checked = $(this).is(':checked');
$('.selectedId').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
}
else {
checkBox.prop('checked', false);
}
});
});
});
JsFiddle http://jsfiddle.net/Ra3uL/
You can simply add the handle function to the click event on the select all checkbox:
$('#chk-all-items').click(selectAll);
And then this function should be enough to select all or unselect all.
selectAll = function (event) {
var self = this;
$('.template-item-select').each(function () {
this.checked = self.checked;
});
}
It is because the method selectAll
is not avaible in the global scope.
In the second dropdown in the left panel Frameworks and Extensions
, select no -wrap head/body
it will work fine.
The reason being by default onload
is selected and when onload is selected all the entered script is wrapped inside a anonymous function as given below. It will make the selectAll
function a local method inside the anonymous function, thus your onclick event handler which uses global scope will not get access to the method causing an Uncaught ReferenceError: selectAll is not defined
error.
$(window).load(function(){
//Entered script
});
Demo: Fiddle
Update But you can simplify it as
$(function(){
$('#selectall').click(function(i, v){
$('.selectedId').prop('checked', this.checked);
});
var checkCount = $('.selectedId').length;
$('.selectedId').click(function(i, v){
$('#selectall').prop('checked',$('.selectedId:checked').length == checkCount)
});
});
and remove all the onclick
handlers from input elements as shown in this demo