6 marca 2013

jQuery live input value reading (keydown, keypress & keyup story)

When I tried to get advantages of getting input field changes after each key I met some problems. To make this description short I do not present examples of my problems, but leads you to final solution.

Solution:
    $(function () {
      $("#m1").keydown(function(){
        that=this;
        setTimeout(function(){
          $("#m1s").text(
            that.value ? that.value : ""
          )
        },0)
      });
    }
    );

HTML content:
  <label for="m1">Test input: </label><input id="m1" placeholder="type here" />
  <hr>
  <span id="m1s">&lt;empty&gt;</span>

Explanation:

  1. When key event is triggered it is not applied to control, because you can prevent default browser reaction in handler. The only key event triggered after value changed is keyup. It is not nice to update information only when key is released.
  2. Using setTimeout with 0ms delay gives browser opportunity to apply default key handlers and update control content (value).
  3. God candidate to be used is keypress event, but... in some browsers keypress is not triggered for character removing keys. Keydown event is triggered for removing character as well, so it is final choice.
Doubts:
It is not sure, that keydown event is triggered when key is repeated by log press keyboard. It works for me so fat.

Here you can see working example: http://jsbin.com/

Brak komentarzy:

Prześlij komentarz