w3resource

jQuery: Append an element with a text message when an input field is changed

jQuery Events : Exercise-3 with Solution

Append a <p> element with a text message when an <input> field is changed.
Sample Data :

HTML :

<body>
  <form  name='demo_form'>
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
  </form>
  </body>
  

Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Append a <p> element with a text message when an <input> field is changed</title>
</head>
<body>
<form>
<input id="field1" type="text" value="Field 1">
</form>
</body>
</html>

JavaScript Code :

$( "#field1").change(function() {
  $( "<p>The text has changed.</p>" ).appendTo( "body" );
});

Note: In jQuery appendTo() method is used to insert every element in the set of matched elements to the end of the target.

Live Demo:

See the Pen jquery-events-exercise-3 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Attach a function to the blur event. The blur event occurs when the following <input> Field1 loses focus.
Next: Hide all headings on a page when they are clicked.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/jquery-exercises/jquery-events-exercise-3.php