Write jQuery code to show the remaining characters of a textarea
Description: The textarea allows 50 characters. Show “N characters left” below it.
Hint:
- Use the length of
.val()in theinputevent.
HTML of the page
<textarea id="msg" maxlength="50"></textarea>
<p id="left">50 characters left</p>
Solution
var max = 50;
$('#msg').on('input', function () {
var left = max - $(this).val().length;
$('#left').text(left + ' characters left');
});
$('#msg').val('Hello jQuery world').trigger('input');
HTML after the code runs
<p id="left">32 characters left</p>
How it works
- The text has 18 characters, so 32 are left.
- The
maxlengthattribute in the HTML stops the typing at 50.
Read jQuery Forms.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |