7

I have a side menu of which you can right-click and choose to rename. This removed the <a href="... from the <li></li> and adds an input field. I cannot seem to have this appended input do anything however it seems I can get this to work on inputs of which have not been appended.

$('.ShowInput').click(function(e) {
    $('body').html("<input type='text' value='search' class='search'>");
});
$("input").on("keydown",function search(e) {
    if(e.keyCode == 13) {
        alert($(this).val());
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="ShowInput">
  Click to show input
</div>

2
  • Hello, I am not sure what you are asking, do you only want to keep the <a href="..."?
    – shell
    Commented May 17, 2016 at 0:58
  • @shell I want to fire an event on enter of the appended <input> field.
    – user2199267
    Commented May 17, 2016 at 1:00

2 Answers 2

8

Try binding your keydown event to an ancestor element, and pass your input with the search class as an argument to the .on() method.

$("body").on("keydown", "input.search", function (e) {
  var inputValue = $(this).val(); 
  if(e.keyCode == 13) {
    alert(inputValue);
  }
});
1
  • This works perfectly! Thank you
    – user2199267
    Commented May 17, 2016 at 1:07
4

Use following way to bind events for dynamically added elements. Reference: Event binding on dynamically created elements?

$('document').on('keydown', '.search', function() {
   if(e.keyCode == 13) {
        alert($(this).val());
    }
});
1
  • 1
    $(document).on('keydown', '.search', function() { if(e.keyCode == 13) { alert($(this).val()); } });
    – StanleyD
    Commented Jun 28, 2019 at 8:46