Home > database >  How to make an array of IDs be the id of my onchange?
How to make an array of IDs be the id of my onchange?

Time:10-20

What happens is: I create a bunch of inputs with jQuery, they can have different IDs. In them, I need to put an alert on a certain value when onChange() happens, how can I do that? A shallow example of this is the code below that I'm trying.

let exemploIds = ['id1', 'id2', 'id3', 'id4', 'id5', 'id6'];

exemploIds.forEach(function(point) {
  $('#inputs').append(`
    <input id="${point}" type="number">
  `)
});

exemploIds.forEach(function(point) {
  $('#'   point).on('change', function() {
    if ($(this).val() > 100) {
      alert('Very high!')
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="inputs"></div>

CodePudding user response:

I recommend you add a class to your <input> fields and add an input event listener to that selector.

After the changes, you will notice that the ID is no longer needed.

const exampleIds = ['id1', 'id2', 'id3', 'id4', 'id5', 'id6'];

function createInputFromId(id) {
  return $('<input>', { id, type: 'number', class: 'number-input' });
}

function onInputChange(e) {
  if (parseInt($(e.target).val(), 10) > 100) {
    console.log('Very high!')
  }
}

$('#inputs').append(exampleIds.map(createInputFromId));
$('.number-input').on('input', onInputChange);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="inputs"></div>

CodePudding user response:

Event delegation is the way to go here, but to continue with your method, you can simplify your code a bit by doing it all in one loop:

let exemploIds = ['id1', 'id2', 'id3', 'id4', 'id5', 'id6'];

exemploIds.forEach(
  function(point) {
    $('#inputs').append(
        $('<input>', { id: point, type: 'number' }).on('change', function() {
          if ($(this).val() > 100) {
              alert('Very high!')
          }
      })
     )
  }
)

You can even omit the array if you know there will be exactly six <input> fields whose IDs are id1...id6:

for (let id=1; id <= 6; id  ) {
  $('#inputs').append(
      $('<input>', { id: 'id' id, type: 'number' }).on('change', function() {
        if ($(this).val() > 100) {
          alert('Very high!')
        }
      }
    )
  )
}
  • Related