views:

230

answers:

1

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 I try? If you need further explanation feel free to ask.

edit: btw, all of this is in $(document).ready()

+1  A: 

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");
        }
}
Shawn Steward
That looks very nice, but it is not working at all. I am going to keep messing with it and see where I can get. Will post if I find a solution. FYI, I get an error that says el.change() is not a function.
Jacob Huggart
After playing with this some more and rearranging a little bit, I got it working.If anyone wants the final code, just let me know.
Jacob Huggart
Sorry about that, like I said my jQuery syntax isn't the best. Post the working code in your initial post and I'll update mine. Glad to hear you got it working!
Shawn Steward