0

I wrote the keyup event in an external js file and it's referenced in the html file.

$('input[name=restaurant]').keyup(function(event){
    console.log("keyup");
});

The strange thing is that it won't activate unless I include it in document ready function.

$(document).ready(function(){
    $('input[name=restaurant]').keyup(function(event){
        console.log("keyup");
    });
});

The keyup event worked just fine outside of document ready function before. I don't know what the problem is now.

1 Answers1

1

Because at the time your script ran, the element wasn't in the DOM yet. Thus, $('input[name=restaurant]') doesn't select any element, and no event listener is attached.

$(document).ready() waits for every element in the DOM to finish loading, then executes the callback.

See: Document: DOMContentLoaded event

Spectric
  • 30,714
  • 6
  • 20
  • 43