RyanZ
RyanZ

Reputation: 21

Jquery - Display value of user input live

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?

Upvotes: 2

Views: 2407

Answers (3)

tabz100
tabz100

Reputation: 1473

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.

Upvotes: 3

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

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>

Upvotes: 0

Red2678
Red2678

Reputation: 3287

$(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>

Upvotes: 0

Related Questions