Ad

JQuery Handler To Know When At Least 1 Character Has Been Typed Into An Input Text Element

- 1 answer

I have a simple input like the following:

<input type="text" id="foo">

I tried using change() in order to detect when at least 1 character has been keyed in. The problem is, the event doesn't fire off until the input text box has lost focus.

Is there another event I can bind to and be able to trigger some code when at least 1 character has been typed?

Ad

Answer

You can use jQuery's keydown(). You can also try keypress(), which fires when the key is down, or keyup(), which is when the key is lifted up.

These all fire after a single key, not upon losing focus.

Therefore, you can try:

$("#test").keydown(function() {
  $("#console").prepend(
    (($(this).val().length) ?
      "Not Empty" :
      "Empty")
    + "<br />"
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" />
<div id="console"></div>

Ad
source: stackoverflow.com
Ad