views:

242

answers:

2

First, housekeeping: A quick review makes me think this isn't a duplicate but would be happy to be corrected.

I've got an ASP.NET MVC app that have a page with multiple forms, each form has some text fields, an agreement checkbox and a submit button. I'd like to disable the submit button if the agreement checkbox isn't checked individually for each form. I've got it working but I get the feeling that I'm missing something elegant and I know there are people here far better at JQuery than I.

Here's the code I've got working:

    $(function() {
        $("form").each(function() {
            $("#Agreement", this).click(function() {
                if (this.checked) {
                    $($($(this).parent().get(0)).find("input:submit").get(0)).attr("disabled", "");
                } else {
                    $($($(this).parent().get(0)).find("input:submit").get(0)).attr("disabled", "disabled");
                }
            });
        });
    });

You can see that the code runs at page ready, selects all the 'form's on the page and attaches a click handler to each of the agreement checkboxes within each form. What I've struggled with, and what looks particularly inelegant, is the method of getting from the checkbox object that triggered the click event back to the parent form object and then to the sibling (of the checkbox) submit button to disable it. If anyone can come up with a better solution then I'm ready to be educated!

+1  A: 

something like this might be better:

$(function() {
    $("form").each(function() {
        $("#Agreement", this).click(function() {
            $('input:submit', this.form).attr("disabled", this.checked ? "" : "disabled");
        });
    });
});

It looks like you're re-using id="Agreement" within each form - you shouldn't do that.

You could even do this if you change id to class:

$(function() {
    $("form .Agreement").click(function() {
        $('input:submit', this.form).attr("disabled", this.checked ? "" : "disabled");
    });
});
Greg
A: 

I would approach it by having a function disableSubmit(objId, checkState), then actually just coding on each checkbox an attribute onclick="disableSubmite('submit1', this.checked);

disableSubmit(objId, checkState)
{
   $(#objId).attr("disabled", checkState ? "" : "disabled");
}

Jquery is cool, but sometimes you just need to attach the JS directly to the object that fires it off.

Russell Steen