2

Similar to Stack Overflow, I'm trying to create a jquery method that records and displays the value of what a user enters into an <input type='text'> field.

<form>
  Language:</br>
  <input type="text" language="language">
  <input type="submit" value="submit">
</form>

<p>
</p>

<script>
  $(document).ready(function () {
    $(":text").keypress(function () {
      $("p").text($(":text").val());
    });
  });
</script>

It accurately records the correct value, but it is one step too slow. If I type in a first character, it doesn't show up, but after I type in a second character, only the first character is recorded. If I type in 3 characters, the first 2 are recorded, etc.

How can I fix this?

3 Answers 3

3

Try to bind the event to the keyup event

<form>
  Language:</br>
  <input type="text" language="language">
  <input type="submit" value="submit">
</form>

<p>
</p>

<script>
  $(document).ready(function () {
    $(":text").keyup(function () {
      $("p").text($(":text").val());
    });
  });
</script>

According to the jQuery docs: Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

Sign up to request clarification or add additional context in comments.

2 Comments

I see, the keyup event is different than the keypress event.
keypress event is fired when a key is pressed. The moment you press a key, that character has not been written into the input yet. That is why if you immediately call val() on keypress, it returns the value without the pressed key.
0

$(document).ready(function () {
    $(":text").keyup(function () {
      $("p").text($(":text").val());
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  Language:</br>
  <input type="text" language="language">
  <input type="submit" value="submit">
</form>

<p>
</p>

Comments

0

You could also make a jQuery plugin.

$.fn.bindTo = function(element) {
  $(this).keyup(function() {
    element.text($(this).val());
  });
};

$(document).ready(function() {
  $("#input").bindTo($("#output"));
});
label {
  display: inline-block;
  width: 60px;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label for="input">Input:</label>
  <input id="input" type="text" language="language">
  <br />
  <label for="output">Output:</label>
  <span id="output"></span>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.