views:

292

answers:

2

I am using Jquery form validation plug-in to validate inputs within a form before submitting, there are some input elements which are named as "question1”, "question2", "question3",..., they are dynamically generated. So how to validate these input elements within the Jquery plugin function validate()? I need a means to select them first.

$(document).ready(function() {
    $("#formname").validate({
        rules: {
            title: {
                required: true,
                minlength:40
            },
            content: {
                required: true,
                minlength:100,
                maxlength:2000
            }
        },
        messages: {
        }
    });
});

Title, content are other input elements within the same form, they are not dynamically generated so they are easy to validate, just by their name. So how to validate "question1", "question2", "question3",..., certainly I can write like this:

 question1: {
                required: true,
                minlength:40
            },
      question2: {
                required: true,
                minlength:40
                    },
         question3: {
                required: true,
                minlength:40
            },
         ...

But, as I said, these input elements are dynamically generated, I can not predict how many "questionn" there are. So how to do the job?

A: 

You have to put a class="question" attribute on each of the dynamically-created elements so that you can perform a jQuery selector against them.

$("#question").validate({  ..etc
Robert Harvey
I want to refer to those input elements within the function of$("#formname").validate({rules:{}});
Steven
Then you need a subselector. My jQuery-foo is failing me at the moment, but I can look it up tomorrow. It is something like $("Formname question").validate( ..etc
Robert Harvey
A: 

I hope I understand the question:

You could just write in an OnChange handler into each element that is created. This would then call a validation routine for you. It's not the unobtrusive approach that you get by binding validation to elements, but it works.

JQuery tries to assist with dynamic elements using this: http://docs.jquery.com/Events/live#typefn

But .live doesnt support change events at the moment.

Another library might. Google around and see.

firecall