3

I have one input with class validate and I'm appending more with same class dynamically.

$('body').on('change', $('.validade'), function() {
    var value = $(this).val();
    var IsValid = TestValue(value);
    console.log(IsValid);
});

This works event fires for all inputs added but does not bring the value. If I use:

$(".validate").change(function(){
    var value = $(this).val();
    var IsValid = TestValue(value);
    console.log(IsValid);
});

The value is ok but only works for the first input. Should I place this on the $(document).ready(function() {});? I've tried but same result.

GG.
  • 17,726
  • 11
  • 69
  • 117
rgomez
  • 123
  • 2
  • 15

3 Answers3

2

The change() will not work since the elements are dynamically generated, so you should use the event delegation .on() as you show in the first example to deal with them :

$('body').on('change', '.validade', function() {
    var value = $(this).val();
    var IsValid = TestValue(value);
    console.log(IsValid);
});

Hope this helps.

Zakaria Acharki
  • 63,488
  • 15
  • 64
  • 88
0

You passed jQuery object as second parameter to on, but as you can read here, this should be a selector:

$(element).on( events [, selector ] [, data ], handler )

So, as you can imagine @Zakaria's solution will work (if you using jQuery +1.7), otherwise you need to use delegate instead.

Related on stackoverflow:

Community
  • 1
  • 1
Mehdi Dehghani
  • 8,186
  • 5
  • 49
  • 53
0

If you Java Script code begins before HTML tags on which you will work then you need this - $(document).ready(function() {}); - to say to the engine that begin work as soon as possible. (onload event occurs later, when all content (e.g. images) also has been loaded). If js code on the end of HTML then meaningless this function.

But for dynamically generated element you have to use

$(document).on('action','selector',function(){});

$(document).on('change', 'selector', function() {
    var value = $(this).val();
    var IsValid = TestValue(value);
    console.log(IsValid);
});

As regards to selectors, best practice says that for

  • for Unique elements use "ID"
  • for Design purposes use "class"
  • for Similar dynamic elements use "attribute"
Musa
  • 2,120
  • 23
  • 22