1

I have made a keyup event listener on classes called userInput, but after appending multiple input boxes with the same class, this event listener will not fire from the new input boxes.

HTML

<div id="wrapper">
    <input type="text" class="userInput">
    <button type="button" id="add_input">Add</button>
</div>

Javascript

$(document).ready(function(){
    $(".userInput").on("keyup", function(){
        alert("Key has been released");
    });   

    var target = $("#wrapper"),
        innerHTML = "<div><input type=\"text\" class=\"userInput\"></div><br>";
    $("#add_input").on("click", function(){
        target.append(innerHTML);
    });
});

The event listener fires for the original input box, but doesn't for any of the new appended input boxes which have the same class.

JimiiBee
  • 159
  • 4
  • 14
  • Sorry it's a dupe, I couldn't really find a similar problem on here but I guess I wasn't looking hard enough – JimiiBee Feb 11 '15 at 19:28

1 Answers1

1

Use event delegation:

$(".wrapper").on("keyup", ".userInput", function(){
    alert("Key has been released");
});   
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304