Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Dynamically adding validation rule to multiple textboxes

Tags:

jquery

I'm trying to add a validation rule to multiple textboxes dynamically. Here's the js:

            //validate form.
            $("#SubmitForm").validate();
            $("input[id*=Hours]").rules("add", {
                number: true,
                messages: {
                    number: "Please enter a valid Hours"
                }
            });

This applies the rule to the very first textbox on the page with "Hours" in the id but then it doesn't apply it to any of the other ones.

Anyone know what's wrong here?

Thanks, Justin

like image 744
Justin Avatar asked Jun 14 '10 02:06

Justin


1 Answers

You can add the rule to each item matched by the wildcard selector with .each(), like this:

$("#SubmitForm").validate();
$("input[id*=Hours]").each(function() {
    $(this).rules("add", {
        number: true,
        messages: {
            number: "Please enter a valid Hours"
        }
    });
});

Hope this helps !

like image 130
Valentin Flachsel Avatar answered Oct 26 '22 20:10

Valentin Flachsel