PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] How to add KeyUp event to dynamically added INPUT

 October 15, 2022     dom, jquery, jquery-events     No comments   

Issue

There is a table that has dynamically added rows in this way:

var hTML=   '<tr> \
            <td class="cell1"><input id="tblJENazwa-' + i + '" type="text" style="background-color: #f0f0f0;" disabled></input></td> \
            <td class="cell2"><input id="tblJEKalorie-' + i + '" type="text" style="background-color: #f0f0f0;" disabled></input></td> \
            <td class="cell2"><input id="tblJEWaga-' + i + '" class="JEWedit" type="number" min="0"></input></td> \
            </tr>'
$('#tblJadlospisEdycjaT1 tbody').append(hTML);

The input that I need the data from is #tblJEWaga-'i' where 'i' is is between 0 and 100+, and has class .JEWedit I wanted to use this class and create an even handler for KeyUp event. I tried to do this in the following way:

$('.JEWedit').keyup(function(){
        clearTimeout(typingTimer);
        console.log("attr ID=",$(this).attr('id'));
        if ($('.JEWedit').val()) {
            typingTimer = setTimeout(doneTypingT, doneTypingInterval);
        }
    }); 

...but... this does not work at all.

Could you please advice on how to create on KeyUp event handler in order to track #tblJEWaga-'i' changes?


Solution

This is where Event Delegation comes in handy. Since there are unknown (0 or more) .JEWedit elements available when your page loads, defining your event as $('.JEWedit').keyup() won't work for any that are added after the fact. Simply define your event as such:

$('body').on('keyup', '.JEWedit', function () {
  clearTimeout(typingTimer);
  console.log("attr ID=", $(this).attr('id'));
  if ($('.JEWedit').val()) {
    typingTimer = setTimeout(doneTypingT, doneTypingInterval);
  }
}

Now, this keyup event will be available to any .JEWedit, so long as it is appended anywhere in your <body> element.



Answered By - Tim Lewis
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing