1

I have a textbox. If selected and hit the tab key, a new line will open. This works fine so far. However, the same action doesn't work in that dynamically created textbox. Even if it has the same class which the original textbox was called on. I tried to find the explanation on the internet, but I couldn't get/understand a right answer. Could someone please help me?

http://jsfiddle.net/RzCLM/1/

$('.list').keydown(function(key){
    if(key.which === 9) {
        $('.ingredients_list').append('<li><input class="list" type="text"/><i><img class="remove" src="images/remove.svg"></i></li>');

    }
}); 
sjoerdvanhoof
  • 111
  • 2
  • 11

2 Answers2

1

Use $(document).on to target dynamically created elements:

$(document).on('keydown', '.list', function(key){
    if(key.which === 9) {
        $('.ingredients_list').append('<li><input class="list" type="text"/><i><img class="remove" src="images/remove.svg"></i></li>');

    }
}); 

jsfiddle.

vsr
  • 3,138
  • 1
  • 19
  • 14
0

That's because you need to use event delegation as the new .list elements do not exist at the time your .keydown() is executed, change your code to:

$(document).on('keydown','.list',function(key){
        if(key.which === 9) {
            $('.ingredients_list').append('<li><input class="list" type="text"/><i><img class="remove" src="images/remove.svg"></i></li>');

        }
    }); 

JSFiddle Demo

DarkAjax
  • 15,955
  • 11
  • 53
  • 65