Home > database >  Firing keyup event on multiple input text with same class
Firing keyup event on multiple input text with same class

Time:05-30

I have this scenery:

<input type="text" id="quantity_2" maxlength="99"  value="0">
<input type="text" id="quantity_17" maxlength="99"  value="0">
<input type="text" id="quantity_16" maxlength="99"  value="0">

where I am trying to fire a keyup event showing an alert with this:

$(function() {

    $('input:text.qty_item').on('keyup', function() {
        alert("clicking quantity field!....");
    });

});

but it doesn't show any alert... shouldn't this identify where from it's pressed a key and fire the alert or having same class name on all inputs makes jquery confusing to identify the element where it was pressed the key?

Thanks in advance to all! Cheers! :-)

CodePudding user response:

Consider the following code.

$(function() {
  $("input[type='text'].qty_item").keyup(function() {
    console.log("Key Up - "   $(this).attr("id"));
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="quantity_2" maxlength="99"  value="0">
<input type="text" id="quantity_17" maxlength="99"  value="0">
<input type="text" id="quantity_16" maxlength="99"  value="0">

This works as expected. You may want to consider not using pseudo selectors like :text.

If you need to use Delegate assignment, for dynamically created items, select the closest static parent element.

$(function() {
  $(document).on("keyup", "input[type='text'].qty_item", function() {
    console.log("Key Up - "   $(this).attr("id"));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="quantity_2" maxlength="99"  value="0">
<input type="text" id="quantity_17" maxlength="99"  value="0">
<input type="text" id="quantity_16" maxlength="99"  value="0">

  • Related