R K R K - 15 days ago 7
Javascript Question

Counting remaining characters on keyup

I want to write a program that calculates the length of the remaining characters while I type in the textbox.

But the code is not working.

Below is the

html code
.

<!DOCTYPE html>
<html lang="en">
<head>
<title>
</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/custom.css" />
</head>
<body>
<textarea rows="10" cols="30" maxlength="100">
</textarea>
<p id="area_description"></p>
<script type="text/javascript" src="js/jquery-3.1.1.min.js" ></script>
<script type="text/javascript" src="js/custom.js" ></script>
</body>
</html>


Below is the code in
custom.js


$(document).ready(function(){
$('#area_description').html('100 characters remaining.');
$('textarea').on('keyup',function(){
var x = $('textarea').val().length();
var y = 100-x;
$('#area_description').html(y+'characters remaining');
});
});


I am a beginner in jquery.

For any query, please comment below.

Answer

You have a typo. Replace .length() with .length.

$(document).ready(function(){
  $('#area_description').html('100 characters remaining.');
  $('textarea').on('keyup',function(){
    var x = $('textarea').val().length;
    var y = 100-x;
    $('#area_description').html(y+'characters remaining');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="10" cols="30" maxlength="100">
</textarea>
<p id="area_description"></p>