Jay mun Jay mun - 1 year ago 54
jQuery Question

get the index of dynamic input array using in jquery validate plugin

am trying to get the index of dynamic input tags


  1. html

    <input type="text" name="test[]" value='1'>
    <input type="text" name="test[]" value='2'>
    <input type="text" name="test[]" value='3'>

  2. validate.js

    rules: {
    "test[]" : {
    required : true
    }
    },
    messages: {
    "test[]" : {
    required : function ( r, i ) {
    return " the [index]st input required";
    **// i need to get the index of the current input(or select) tags**
    }}}


Answer Source

The second argument to the callback function is the element. You can use the jQuery .index() method to get its index within the collection.

messages: {
    "test[]": {
        required: function(params, element) {
            var index = $("input[name=test\[\]]").index(element) + 1;
            return "Input #" + index + " required";
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download