jarrod wrote:

I'm trying to write a script that responds to a keyup event in any field of a
given form. If the form is valid, the submit button of that form is enabled.
The problem is that there are several forms on the page. My script has to
enable the right one.

I have a way that works, but it's complicated. Can someone suggest a better
way?

The essence is that I first get the "name" attribute of the form with
"this.form.name". Then I use the name in a jQuery selector...

$('[EMAIL PROTECTED]' + formName + '] [EMAIL PROTECTED]')

Here it is with some context...

Bind the keyup function...

$(document).ready(function(){
$("form :input").keyup(function(){
        updateFormEnabled(this.form.name);
    });
}

function updateFormEnabled(formName)
{
    if (isFormValid(formName))
    {
        $('[EMAIL PROTECTED]' + formName + ']
[EMAIL PROTECTED]').removeAttr("disabled");
        $('[EMAIL PROTECTED]' + formName + ']
[EMAIL PROTECTED]').removeClass('formfielddisabled');
    } else {
        $('[EMAIL PROTECTED]' + formName + '] [EMAIL PROTECTED]').remove();
        $('td#submit_td_' + formName).append("<input class='ordinaryButton
formfielddisabled' disabled='disabled' name='commit' type='submit'
value='Add user' />");
    }
}

The isFormValid(formName) function also uses the same way of finding which
form to examine.


This seems a little too complex to me. this.form already is a reference to the element you need and you can use that as a context for a search.

$(document).ready(function() {
    $("form :input").keyup(function() {
        updateFormEnabled(this.form);
    });
});

function updateFormEnabled(form) {
    var input = $('[EMAIL PROTECTED]', form);
    if (isFormValid(form)) {
        input.removeAttr('disabled').removeClass('formfielddisabled');
    } else {
        input.remove();
        $('#submit_td_' + form.name).append(...);
    }
}

Note that I'm also caching the query in the variable input, instead of repeating the statement three times and performing the search twice in the if-branch (plus chaining). That should perform a bit better.

Moreover the selector "#id" is slightly faster than "td#id".


--Klaus




Reply via email to