Jordan Baron
Jordan Baron

Reputation: 165

Textarea keypress not working

My code won't work. It's supposed to alert whenever a user presses a key while focused inside of a textbox element!

$("#yourcode").keyup(function() {
        alert("I found Hogwarts.");
});

Upvotes: 0

Views: 2588

Answers (1)

jeremykenedy
jeremykenedy

Reputation: 4275

You need to wait until the DOM is ready before adding the keyup handler. This can be achieved by calling .ready() after using $() to get a DOM reference to the document (i.e. $(document)). Also make sure you load jQuery before you load the script:

JS:

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>


<script>
    $(document).ready(function(){
        $("#yourcode").keyup(function() {
                alert("I found Hogwarts.");
        });
    });
</script>

HTML:

<textarea id="yourcode"></textarea>

Here is a working example (also available in this jsFiddle):

$(document).ready(function(){
  $("#yourcode").keyup(function() {
    alert("I found Hogwarts.");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="yourcode"></textarea>

Upvotes: 2

Related Questions