How to implement a keyup function with dynamically creating an input element using jQuery?

I cannot understand why the following code does not work. JSFIDDLE LINK

$(document).ready(function () { addInput(); }); var limit = 30; function addInput() { var numberOfRows = $("#shipping tr").size(); var id = numberOfRows; if (numberOfRows == limit) { alert("You have reached the limit of adding " + limit + " inputs"); } else { $('#shipping').append('<tr id="rate' + id + '"></tr>'); $('tr#rate' + id).append('<td></td>'); $('tr#rate' + id).append('<td><input type="text" name="rate" /></td>'); } $('input[name=rate]').on('keyup', 'input', function () { alert('YAY'); return false; }); } 

I am trying to assign a keyup function to inputs that I am adding dynamically.

Expected Result: YAY! inside popup

Please, help!

+4
source share
2 answers

Attach a keyup event handler to the delivery table, and the event will bubble from the table input[name="rate"] to shipping:

 $('#shipping').on('keyup', 'input[name="rate"]', function () { alert('YAY'); return false; }); 

Demo

+7
source

You need to add delegation to document because it is added to document .

Example

 $(document).on('keyup', 'input[name="rate"]', function () { alert('YAY '); }); 

Working Demo

+3
source

All Articles