1

So the page I'm creating has a button which will add input fields as needed. It looks like

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <input type="text" placeholder="Name">
    <button id="add-name" type="button">+</button>
    <div id="preview"></div>
</body>

</html>

Then there's some jquery to make the button add a new input field, and for any values in the input fields to be reflected in the preview div.

$(document).ready(function () {

    $("#add-name").click(function () {
        $(this).before("<input type='text' placeholder='Name'>");
    });

    $("input").keyup(function () {
        $("#preview").html($(this).val());
    });

}

When I add another input via the button, that input doesn't trigger the keyup event when I type into it. Why is this, and what can I do about it? Thanks!

Also, this is a heavily oversimplified example I wrote for this question. I know this doesn't look too pretty but it's simple to help me understand what's happening.

Padaca
  • 337
  • 1
  • 6

1 Answers1

2

Event handlers are bound only to the currently selected elements

To attach event to the elements that are added to the document at a later time try Delegated event handlers approach using .on():

$("body").on("keyup", "input",function () {

$(document).ready(function () {

  $("#add-name").click(function () {
    $(this).before("<input type='text' placeholder='Name'>");
  });

  $("body").on("keyup", "input",function () {
    $("#preview").html($(this).val());
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Name">
<button id="add-name" type="button">+</button>
<div id="preview"></div>
Mamun
  • 66,969
  • 9
  • 47
  • 59