Miguel Stevens
Miguel Stevens

Reputation: 9230

jQuery Validate plugin with multiple select boxes

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!

Upvotes: 4

Views: 17391

Answers (2)

Sparky
Sparky

Reputation: 98748

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/

Upvotes: 14

Henry Gibson
Henry Gibson

Reputation: 2058

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()

Upvotes: 0

Related Questions