Skip to content
Advertisement

JQuery validate dynamically added input fields against other dynamically added input fields

I have multiple pairs of input fields for start and end dates:

JavaScript

I’m using jQuery’s validator.AddMethod to validate that the end date is after the starting date:

JavaScript

The problem is the validation is always comparing the end dates to the first starting date. I want each end date to be compared to it’s relevant starting date.

I’m still a newbie in javascript but I know that this is probably caused by the id being the same for all the startDate inputs, which is illegal html.

Is there a way to fix this? Thanks!

Advertisement

Answer

the problem with your code is you are referencing always the same id StartDate so its normal the validation is always from the same startdate. When you have lot of same id the search of id stops always at the first.

JavaScript

and you have the same id for different tag, its not good in html.

in your validator, you reference the StartDate id

JavaScript

one solution will be to create an id indexed :

JavaScript

you adapt the validator to trap the right id.

i suggest you to create an attribute data-id for example, and you put the id of StarDate: so in validator you trap the id of right date

JavaScript

and you modify the loop:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement