skip to Main Content

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


  1. 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 the index of the foreach loop will always default to 0 to fix this is simple change the name from index to for ex i $.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

    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(data){
                        console.log(index);   // the index you will get here is the index of the outer loop
                        document.getElementById("txt_sumberdaya"+[index]).value = data['TEXT'];
                    });
                    }
                });
            });
        }
    
    Login or Signup to reply.
  2. Use event delegation. When an event happens in Javascript it "bubbles up" to parent elements. This means that if you have:

    <div id="foo"><!-- lots of inputs --></div>
    

    You can use a single event listener for all of them:

    $('#foo').on('change', 'input', (e) => // ...
    

    But how do you know which input triggered the event? That e argument will have both target and currentTarget 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 use this to refer to the input.

    For more info see: https://learn.jquery.com/events/event-delegation/

    Login or Signup to reply.
  3. 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.

    $('.txtLini', document).each(function(index, item) {
      $(item).on('change', function() {
        var lini = this.value;
        $.ajax({
          url: 'https://jsonplaceholder.typicode.com/posts/' + (index + 1),
          method: 'get',
          // data: {
          //   lini: lini
          //  },
          //  dataType: 'json',
          success: function(response) {
           // console.log($('#txt_sumberdaya' + (index + 1)));
            $('#txt_sumberdaya' + (index + 1)).val(JSON.stringify(response));
          }
        });
      });
    
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>
      INput : <input type="text" id="txtLini1" class="txtLini" /> Copy input : <input type="text" id="txt_sumberdaya1" class="txt_sumberdaya" />
    </div>
    
    <div>
      INput : <input type="text" id="txtLini2" class="txtLini" /> Copy input : <input type="text" id="txt_sumberdaya2" class="txt_sumberdaya" />
    </div>
    
    <div>
      INput : <input type="text" id="txtLini3" class="txtLini" /> Copy input : <input type="text" id="txt_sumberdaya3" class="txt_sumberdaya" />
    </div>
    
    <div>
      INput : <input type="text" id="txtLini4" class="txtLini" /> Copy input : <input type="text" id="txt_sumberdaya4" class="txt_sumberdaya" />
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search