Atlas Atlas - 3 months ago 7
Javascript Question

Keypress check not working

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;
}
});

Answer

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; 
  }
});
Comments