Write jQuery code to show the text typed in an input field

Description: Whatever the user types in the field must also appear in the paragraph below it, at once.

Hint:

  • Use the input event, .val() and .text().

HTML of the page

<input type="text" id="name" placeholder="Type your name">
<p>Hello, <span id="show"></span></p>

Solution

$('#name').on('input', function () {
  $('#show').text($(this).val());
});

$('#name').val('Anita').trigger('input');   // simulate the typing
HTML after the code runs

<p>Hello, <span id="show">Anita</span></p>

How it works

  • The input event fires on every change of the text, also when the user pastes.
  • We use .text() to show the value safely.

Read Mouse, Keyboard and Form Events.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.