0

I'm having trouble figuring out how to make the validation plugin to validate my dynamically created input fields in the form. And yes, I have searched around, so far I can't find any answer that solves my problem. So here it is me asking.

Demo: http://jsfiddle.net/MGbWx/

What I'm trying to do is make item price in the first row required. The newly cloned rows should only make item price required when there is input in one of the other three input fields.

I tried the following.

var itemPropSelector = 'input[name="sku[]"], input[name="itemVariant[]"], input[name="itemQuant[]"]';

$('#item-prop-wrapper').on('keyup', itemPropSelector, function () {
    $(this).closest('.item-prop-body').find('.item-price-input').rules('add', {
        required: true
    });
});

But it doesn't work as what I expect. I've been struggling with this for hours...

Can anyone help me on this? I appreciate it!!

Sparky
  • 94,381
  • 25
  • 183
  • 265
Lancelot
  • 1,265
  • 2
  • 16
  • 26

1 Answers1

5

The jQuery Validate plugin uses the name attribute to internally keep track of input elements. It does not matter how rules are assigned, each input must have a unique name attribute.

Since every cloned row will contain the same name, your approach will always fail. Keep this in mind and simply tweak your code to increment the index number on the name as well as the id. Something like this....

newRow.attr('name', newIDNum);

Although IMO, I would not start any id or name with a number. See: https://stackoverflow.com/a/79022/594235


There is nothing wrong with using the .rules('add') method to add the required rule to these new inputs. However, simply adding the required class or the required attribute to the input element will totally negate the need to use the .rules('add') method in your case.

<input required="required" ...

or

<input class="required" ...

Using these inline HTML attributes to set rules instead of the .rules() method is only a matter of preference or specification. (Some rules are too complex to be declared using HTML attributes)

Community
  • 1
  • 1
Sparky
  • 94,381
  • 25
  • 183
  • 265
  • Wow, thanks a lot. And I just realized a lot of people were asking the similar situation (didn't pay full attention to it...). Now I have other question, how do I make only the vert first (original row) required and the newly cloned row **ONLY** required when there is input in other input fields (SKU, Item Quantities)? – Lancelot Nov 17 '13 at 22:26
  • @Lancelot, You could use `addMethod` to write a custom rule and then use `rules('add')` to declare it on your new rows. – Sparky Nov 17 '13 at 22:29