0

The following code works fine:

$(document).on('click', "input[id='inputfield0']",
   function() {
      myFunction(0); 
});

$(document).on('click', "input[id='inputfield1']",
   function() {
      myFunction(1); 
});

$(document).on('click', "input[id='inputfield2']",
  function() {
     myFunction(2); 
})

I want to remove the repetition, as follows:.

 function oneCall() {
    for (var i = 0; i < 2; i++) {
       $(document).on('click', "input[id='inputfield"+i+"']",
          function() {
             myFunction(i); 
          });
    }
 }

function oneCall();

However, in the new function oneCall(), each time myFunction() is called within the loop, it is being passed a value of 2, rather than being incremented on each call. What is the correct way to restructure this code?

Thanks

user1052610
  • 4,440
  • 13
  • 50
  • 101

1 Answers1

0

Add a class to each input and add the listener on said class.

function myFunction(v) {
  console.log(v);
}

$('.click-listener').on('click', function(e) {
  let $target = $(e.target),
      id = parseInt($target.attr('id').split('-')[1], 10);
  myFunction(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputfield-0" class="click-listener" />
<input id="inputfield-1" class="click-listener" />
<input id="inputfield-2" class="click-listener" />
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132