4

I'm using jQuery Validate to validate my form. The problem is that I have a form with multiple select boxes (dynamic number) and it has a dynamic name -> answers[$question['id']]

I've seen some scripts when there's a fixed name you can use that to address all the input fields like so.

$('#form').validate({
    rules: {
        "answers[]" = "required"
    }
});

But in my example this is not possible, Any ideas? Thanks!

1
  • You have a syntax error. it's field: rule, not field = rule. Commented Sep 25, 2013 at 17:11

2 Answers 2

14

Firstly,

it's not "answers[]" = "required"

it's "answers[]": "required"

Notice the colon in place of your equals sign.

$('#form').validate({
    rules: {
        "answers[]": "required"
    }
});

Secondly, that would only assign the required rule to a single field with name="answers[]".

If you want to easily assign this rule to multiple fields with name="answers[1]", name="answers[2]", name="answers[3]", etc., then you'll need to do one of two things...

1) Declare the required rule inline...

using class:

<input type="text" name="answers[1]" class="required" />
<input type="text" name="answers[2]" class="required" />
<input type="text" name="answers[3]" class="required" />

OR with HTML5:

<input type="text" name="answers[1]" required="required">
<input type="text" name="answers[2]" required="required">
<input type="text" name="answers[3]" required="required">

And jQuery:

$('#form').validate(); // initialize the plugin

DEMO #1: http://jsfiddle.net/7JHWf/


2) Or assign the rule dynamically using the rules() method to all fields with a name starting with answers:

$('#form').validate(); // initialize the plugin

// assign the rules
$('input[name^="answers"]').each(function() {
    $(this).rules('add', {
        required: true
    });
});

DEMO #2: http://jsfiddle.net/7JHWf/1/

Sign up to request clarification or add additional context in comments.

1 Comment

what a great answer. Just what i was looking for!
0

You can just select the select boxes you're interested in by grabbing all select boxes or adding a specific class to them, then using each() to loop through:

$('select') or $('select.specificClass').each(function() {}

You don't need to know the name / id of each box to be able to select and loop through it. You can reference the current item value within the each() loop using:

$(this).val()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.