0

If i add the search bar right away, it works, the console returns the value of the search field every time i press enter, but if i add the search bar after the image was clicked it doesn't work.

http://codepen.io/Nadaga/pen/QEVaGA

$('#glass-image').on('click', function() {
$('#main').html('<input id="search-field" type="text" placeholder="Search"></input>');

})

$('#search-field').keypress(function (e) {
  if (e.which == 13) {
    console.log($('#search-field').val());
    return false;    
  }
});
Atlas
  • 107
  • 2
  • 8

2 Answers2

3

Since, the search-field is dynamically created, It has to be added like this (on the $document),

$(document).on('keypress', '#search-field' ,function(e) {
  if (e.which == 13) {
    console.log($('#search-field').val());
    return false; 
  }
});
David R
  • 14,711
  • 7
  • 54
  • 72
0
$('#glass-image').on('click', function() {
$('#main').html('<input id="search-field" type="text" placeholder="Search"></input>');
  $('#search-field').keypress(function(e) {
  if (e.which == 13) {
    console.log($('#search-field').val());
    return false; 
  }
});
})

Click event only works if the element already exist in html code. So the click event doesn't fire.It won't consider the new element which is created dynamically after the page loaded. Dynamic elements are created with the help of javascript or jquery(not in html).

source: https://stackoverflow.com/a/29674985/1848140

Community
  • 1
  • 1
Nagaraju
  • 1,853
  • 2
  • 27
  • 46