I have a table with a list of 5 items that is dynamically generated using AJAX with a PHP/MySQL backend. Each item has an INPUT Checkbox next to it.
Upon page load, some of the checkboxes must appear "checked" depending on a set of values returned by PHP/MySQL. Thus:
var checked_items = [];
// var checked_items = new Array(); // this is not working either
var GetItemsFromXML;
var SplitItems;
var XMLItemsObj = new Object;
// function...
function DisplayItems() {
CreateRObj(function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
GetItemsFromXML=xmlhttp.responseText; // returns pike delim list
SplitItems = GetItemsFromXML.split("|"); // split at pike
// status - either "all" or "selected"
XMLItemsObj.checkedstatus = SplitItems[0];
// drop last ","
SplitItems[1] = SplitItems[1].substr(0,SplitItems[1].lastIndexOf(","));
// split at comma and pass to variable
checked_items = SplitItems[1].split(",");
}
});
xmlhttp.open("POST","loaditems.php",true);
xmlhttp.send();
}
At this point, the variable "checked_items", contains the values returned by PHP/MySQL. These values will determine which checkbox is checked off.
I've confirmed that this variable is populated by testing to see if it is empty (""), undefined, or null.
Now, Once the page loads, the code below loops through all the checkboxes and checks them off depending on the "XMLItemsObj.checkedstatus" status. If status is "selected", then only some are checked off. If status is "all", all checkboxes are supposed to be checked off.
Here's the code that does this:
if (XMLItemsObj.checkedstatus=="selected") {
for (i=0; i < checked_items.length; i++) {
$(":checkbox[value="+checked_items[i]+"]").attr("checked",true);
}
} else if (XMLItemsObj.checkedstatus=="all") {
$("input:checkbox").each(function() {
$("input:checkbox").attr("checked",true);
});
}
Here's where things start getting weird...
The above only seems to work when I use the "alert" function to check for the values in the "checked_items" variable. It works when ".checkedstatus" is "all" or when i开发者_如何学Pythonts "selected".
Thus, if I were to use, for example this code:
alert("The values of the checked_items variable are: "+checked_items);
Then, the above code will work perfectly.
However, it doesn't work otherwise. Neither when status is "all", nor when status is "selected".
I'm at a loss, but my guess it that the variable is either losing its value, or the event(s) are not being triggered. However, I'm not sure.
Anyone has any ideas? All comments, insights, solutions, and thoughts are welcome. Thanks in advance!
Here is catch Upon page load, some of the checkboxes must appear "checked"
Ensure your script runs when DOM structure of target is created. Then it must work.
精彩评论