I am trying to loop the OnChange method through AJAX call but surprisingly it won’t work.
for (let index = 0; index < 300; index++) {
$('#txtLini'+[index]).on('change', function() {
var lini=this.value;
$.ajax({
url:'<?=base_url()?>index.php/fin/controller/M_index/getKode',
method: 'post',
data: {lini: lini},
dataType: 'json',
success: function(response){
$.each(response,function(index,data){
console.log(index);
document.getElementById("txt_sumberdaya"+[index]).value = data['TEXT'];
});
}
});
});
}
In my javascript above, I’m trying to loop my textbox
id to process in ajax call. I have many ids (txtLini0,txtLini1,txtLini2,etc.)
and many possibilities too in each id user want to choose. Therefore I use id to be a particular variable in OnChange
method. What user type in each id can affect in another id (txt_sumberdaya0, txt_sumberdaya1, txt_sumberdaya2, etc.)
with output in Onchange
Ajax.
I’ve tried to loop just like this but it won’t work as I want.
For example:
If user type in id txtLini0
the output from ajax should be filled in txt_sumberdaya0
. and so on.
But in here my error was when I tried to fill id txtLini1
or txtLini2
the output from ajax still going filled in txt_sumberdaya0
. It seems my index loop still going on 0 every come to ajax success process.
Is there anyone who can fix my code or any other ideas to make it clear?
Thanks.
3
Answers
after looking at your code again the reason you are getting the 0 is because the index passed in your
each
$.each(res,function(index,data)
the index value will depend on the length of the data in your array response so if it’s 1 theindex
of the foreach loop will always default to0
to fix this is simple change the name fromindex
to for exi
$.each(res,function(i,data)
or if you are not using it remove it and pass index directley of the outer loop
your final code should look like this
Use event delegation. When an event happens in Javascript it "bubbles up" to parent elements. This means that if you have:
You can use a single event listener for all of them:
But how do you know which input triggered the event? That
e
argument will have bothtarget
andcurrentTarget
properties, which give you both the element you attached the event handler to, and the element that triggered the event.By using those event properties you should get the correct index for the input that triggered the event. Alternatively, you can also avoid using
=>
functions, and in that case you can just usethis
to refer to theinput
.For more info see: https://learn.jquery.com/events/event-delegation/
You can use below approach using classes to bind an
onChange
event. What you’re doing in AJAX response is wrong. there you don’t need any loop.