JamesG
JamesG

Reputation: 2018

jQuery validation plugin with grouped input elements by name

I have the plugin working correctly for half of my form, but I also have multiple form elements with the same name like so:

               <tr class="orderItems">
                  <td><input type="text" name="code[]" class="codeRowForm" value="" /></td>
                  <td>
                      <select class="selectProductOrders" name="selectProductOrders[]">
                         <option value="default" disabled selected>Select a product</option> 
                     </select>
                  </td>
                  <td><input type="number" pattern="[0-9]*" name="rsp[]" class="rsp" value="" /></td>
                  <td><input type="number" pattern="[0-9]*" name="trade[]" class="trade" value="" /></td>
                  <td><input type="number" pattern="[0-9]*" name="discount[]" class="discount" value="0" /></td>
                  <td><input type="number" pattern="[0-9]*" name="qty[]" class="qty" value="" /></td>
                  <td><input type="number" pattern="[0-9]*" name="cost[]" class="cost" value="" /></td>
                  <td class="deleteOrderRow"><a onclick="return false;" href="#"><img class="addRemoveOrderButton" src="img/deleteOrderRow.png" /></a></td>
              </tr>

This <tr> is repeated multiple times depending on how many order items the user decides to have in the form. So if the names are all the same (for example name=code[] ) in each row, how would I go about applying jQuery form validation using the plugin: docs.jquery.com/Plugins/Validation/validate ??

Thanks

Upvotes: 1

Views: 1538

Answers (1)

Sparky
Sparky

Reputation: 98718

If each name attribute is unique, e.g. code[4], code[9], etc., you get validation to work by enclosing the name with brackets in quotes.

See documentation: "Fields with complex names (brackets, dots)"

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        // your other options,
        rules: {
            'code[1]': {
                // rules
            },
            'code[2]': {
                // rules
            }
        }
    });

});

DEMO: http://jsfiddle.net/TKeEc/

You could also assign rules based on the first part of the name. Assigns the same rule to all fields containing code in the name, e.g. code[4], code[9], etc.

$('[name*="code"]').each(function() {
    $(this).rules('add', {
        required: true,
        // other rules
        messages: {  // optional custom messages
            // custom messages
        }
    });
});

DEMO: http://jsfiddle.net/TKeEc/1/

Otherwise, if you have multiple fields all containing the exact same name attribute, this plugin will not function. You cannot reasonably expect any JavaScript validation to work if you can't target a particular input uniquely. Broken: http://jsfiddle.net/4ZV9D/

Upvotes: 2

Related Questions