I have an ASP MVC web app and on one of the pages there is a set of Main checkboxes with sub-checkboxes underneath them. The sub-checkboxes should only show up when the corresponding main checkbox is checked. I have the following code that works just fine as long as none of the checkboxes are checked when the page loads.
$("input[id$=Suffix]").change(function() {
prefix = this.id;
if (!$(this).hasClass("checked")) {
$("tr[id^=" + prefix + "]").show();
$(this).addClass("checked");
}
else {
$("tr[id^=" + prefix + "]").hide();
$(this).removeClass("checked");
}
});
Now I need to check a database for the values of the main checkboxes. I get the values, and can check the boxes on page load. But when the page comes up, the sub-checkboxes are not displayed when the main checkbox is checked.
Also, if the main checkbox is checked when the page loads, the sub-checkboxes are only displayed when the main chcekbox is unchecked (obviously because the above function only acts on .change()).
What do you all suggest 开发者_如何学JAVAI try? If you need further explanation feel free to ask.
edit: btw, all of this is in $(document).ready()
Your function is only being called on change so it's not firing initially. You'll need something that runs also when the page loads to check for any checked checkboxes and displays the children.
Here's an example of what I mean - instead of just adding the change event, also call update for each one when the page loads. This code may not be exact, I don't have time to test it out right now, but it should get the general idea across. I'm a MooTools guy so forgive me if the jQuery is not exactly right.
$(document).ready(function(){
$("input[id$=Suffix]").each(function(el){
el.change(function(){ updateCheckbox(this); });
updateCheckbox(el);
});
});
function updateCheckbox(chk){
prefix = chk.id;
if (!$(chk).hasClass("checked")) {
$("tr[id^=" + prefix + "]").show();
$(chk).addClass("checked");
}
else {
$("tr[id^=" + prefix + "]").hide();
$(chk).removeClass("checked");
}
}
精彩评论