简体   繁体   中英

How to select elements like question1, question2, question3,… in JQuery form validation plug-in?

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.

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")...

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: {
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM