views:

53

answers:

2

I am using jQuery and the jQuery Validation plugin to validate inputs. Below is the code. Now there are many inputs named like question1, question2, question3, question4,... How can I place validation on them? I mean how to select them all together?

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

The code:

 $("input[name^='question']"): {
            required: true,
             minlength:40

        }

does not work.

A: 

Assuming you mean <input type="text" name="question1" />, then try the following jquery selector:

$("input[name^='question']");

It will return a list of all of those elements.

This is how to do it (assuming the code you posted works for one element):

$(document).ready(function() {
    $("input[name^='question']").validate({
        rules: {
            title: {
                required: true,
                minlength:40
            },
            content: {
                required: true,
                minlength:100,
                maxlength:2000
            }
        },
        messages: {
        }
    });
});
Marius
It is Jquery form validation plugin, not simply Jquery.
Steven
input[name^='question']: { required: true, minlength:40 } does not work.
Steven
No,$("input[name^='question']") are just input elements within the form item, title and content are their peers.
Steven
"item" is the name of a form. Questions elements are inputs within the form of "item".
Steven
Waiting for a solution.
Steven
In that case, there is none.
Marius
+2  A: 

Several ways. You can use the comma separator:

$("#question1, #question2, #question3")...

You can use add():

$("#question1").add("#question2").add("#question3")..

If question1 is a name and not an ID, use an attribute selector:

$(":input[name^=question]")...

But I would recommend using a class:

<input type="text" name="question1" class="question">
<input type="text" name="question2" class="question">
<input type="text" name="question3" class="question">

with:

$(":input.question")...
cletus
Your answer is good, but not what I want. My question is misunderstood by you.
Steven
Some clarification of your question is required in that case.
cletus
I want the selector to be used within $("#item").validate().input[name^='question']: { required: true, minlength:40 } does not work.
Steven
just inputs whose names begin with "question".
Steven
I am using Jquery form validation plugin, the syntax of select is used within the function of validate(), as you can see.
Steven