0

Im appending an input to my html markup but my event listener not working on this input here is my code:

$('button').click(function(){
  $('body').append('<input>')
})
$('input').on('keydown',function(e){
  if(e.keyCode==13){
     alert('ok')
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me</button>
elreeda
  • 4,187
  • 2
  • 16
  • 43
Vettp
  • 1
  • 2
  • 1
    use delegate instead of on – uzaif Apr 11 '16 at 10:18
  • https://www.google.de/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=jquery%20event%20dynamically%20created%20element – Alex Apr 11 '16 at 10:18
  • @uzaif i did its not working http://codepen.io/anon/pen/vGdmRM – Vettp Apr 11 '16 at 10:20
  • `$('body').on('keydown','input',function(e){});` add event like this so that it gets binded to input elements even if they are created later – Developer107 Apr 11 '16 at 10:21
  • $('button').click(function(){ $('body').append('') }) $('body').on('keydown',"input",function(e){ // alert(e.keyCode); if(e.keyCode==13){ alert('ok') } }) – uzaif Apr 11 '16 at 10:25

1 Answers1

0

try event delegation:

$('body').on('keydown','input',function(e){
  if(e.keyCode==13){
     alert('ok')
    }
})
madalinivascu
  • 30,904
  • 4
  • 32
  • 50