I’m trying to loop through the list of forms displayed on the page and append element to each of them depending on their id.
I thought of doing something like this, but it doesn’t seem to be working:
var number_of_forms = $('.common_form_class').length;
if (number_of_forms > 1) {
$('.common_form_class').each(function() {
var identity = $(this).attr('id');
$.getJSON("/token.php?key=" + identity, function(data){
$(this).append('<input type="hidden" class="token" name="token" value="'+data.token+'" />');
});
});
} else {
var identity = $('.common_form_class').attr('id');
$.getJSON("/token.php?key=" + identity, function(data){
$('.common_form_class').append('<input type="hidden" class="token" name="token" value="'+data.token+'" />');
});
}
I understand that I can’t refer to the form within the each() loop by using $(this), but does anyone know how could I achieve this?
I rewrote your code using better style, please test: