Reputation: 185
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.
Upvotes: 3
Views: 44
Reputation: 2662
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
Upvotes: 0
Reputation: 11601
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
:
Upvotes: 0
Reputation: 67505
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.
Upvotes: 2