1

CODE:

var appender = $('<input class="form-control" placeholder="Search" id="search_made" type="text">')
appender.find('#search_made').on('keypress', function(e) {
  e.preventDefault()
  console.log('keypress!')
  if (e.keyCode == 13 && !e.shiftKey) {
    console.log('not shift enter')
    var passed_value = $(this).val()
    if (passed_value === '') {
      console.log('nothing was passed on input tag')
      return false;
    }
    console.log('passed value: ' + passed_value)
  }
})

$('body').append(appender)

I want to add input tag dynamically by jQuery.

Using those code, I can only add input tag seemingly but other functions that has to be bound was not bound well.

So when I type some words on input tag and click enter key, It refreshes page but does not execute any console.log() lines.

How can I fix it to make it do other bound functions(include console.log()) well?

touchingtwist
  • 1,496
  • 3
  • 13
  • 30
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Taplar Oct 04 '18 at 14:51

1 Answers1

3

Change the selector from:

appender.find('#search_made').on('keypress', function(e) {

To

$(document).on('keypress','#search_made', function(e) {

OR: Simply

appender.on('keypress', function(e) {

Working Code Example:

var appender = $('<input class="form-control" placeholder="Search" id="search_made" type="text">')
$(document).on('keypress','#search_made', function(e) {
  e.preventDefault()
  console.log('keypress!')
  if (e.keyCode == 13 && !e.shiftKey) {
    console.log('not shift enter')
    var passed_value = $(this).val()
    if (passed_value === '') {
      console.log('nothing was passed on input tag')
      return false;
    }
    console.log('passed value: ' + passed_value)
  }
})

$('body').append(appender)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Mamun
  • 58,653
  • 9
  • 33
  • 46