0

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>

6
  • There is no HTMLElement.prototype.val. Did you mean $(this).val()? Commented Oct 19, 2022 at 17:43
  • Or perhaps this.value? Commented Oct 19, 2022 at 17:44
  • I mean $(this).val(), sorry, would be this.value if works Commented Oct 19, 2022 at 17:45
  • 2
    Also, you could use event delegation to add one event handler to #inputs and do everything there... Commented Oct 19, 2022 at 17:46
  • 1
    Can you explain what the problem is exactly? Your example already does what you want, no?
    – CherryDT
    Commented Oct 19, 2022 at 17:52

2 Answers 2

1

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>

1

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!')
        }
      }
    )
  )
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.