Accessing Ajax/Dynamic checkboxes
How do I check all checkboxes which have been returned as part of an AJAX request?
I have a page which displays email message summaries (think gmail/yahoo/etc... inbox). Each summary has a checkbox associated with it so that my user could do any number of things with the message. At the top and bottom of the list is a "check all" option. I know how to bind delegate functions to the dynamic checkboxes, but I can't seemt to find any way to give my "Check All" button the ability to manipulate these dynamic elements. Exa开发者_C百科mple:
//get the list of messages
$.ajax({
type: "POST",
url: "GetMessages.asmx/GetMessagePreview",
data: "{'FolderID': '5'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//code here to create a checkbox row (checkbox, message title, etc...)
var cbRow = '<input type="checkbox" class="msg_check" ...etc... />'
//code here to insert to a div or other container
}
});
$("#selectAllButton").click( function(){
????? This is the blank I need filled in...
});
Any help would be greatly appreciated. Thank you.
If you are trying to make the elements that come with the ajax call to inherit the current state of the #selectAll
checkbox, then you need to read that and apply it as you create the new elements.
so
$.ajax({
type: "POST",
url: "GetMessages.asmx/GetMessagePreview",
data: "{'FolderID': '5'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var currentState = $("#selectAllButton").is(':checked') ? 'checked' : '';
//code here to create a checkbox row (checkbox, message title, etc...)
var cbRow = '<input type="checkbox" class="msg_check" '+ currentState +' />';
//code here to insert to a div or other container
}
});
$("#selectAllButton").click( function(){
// the way you normally select your elements..
$('.msg_check')....
});
It should be easy:
$("#selectAllButton").click( function(){
if (this.checked)
$('.msg_check').attr('checked', 'checked');
else
$('.msg_check').removeAttr('checked');
});
Edited: if you want to insert item in the same condition, as all other items (all checked/unchecked), do next:
// ...
var checked = $("#selectAllButton").is(':checked');
var cbRow = $('<input type="checkbox" class="msg_check" />');
cbRow.appendTo(list);
var checkbox = cbRow.find('.msg_check');
if (checked)
checkbox.attr('checked', 'checked');
else
checkbox.removeAttr('checked');
// ...
精彩评论