Category >
JAVASCRIPT
|| Published on :
Wednesday, October 7, 2020 || Views:
927
||
Character Counter using JavaScript
Here Pawan Kumar will explain how to Character Counter using JavaScript
<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Live Demo - Character Counter using JavaScript</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script>
function countChars(obj) {
document.getElementById("charNum").innerHTML = obj.value.length + ' characters';
}
function countChars2(obj) {
var maxLength = 20;
var strLength = obj.value.length;
if (strLength > maxLength) {
document.getElementById("charNum2").innerHTML = '<span style="color: red;">' + strLength + ' out of ' + maxLength + ' characters</span>';
} else {
document.getElementById("charNum2").innerHTML = strLength + ' out of ' + maxLength + ' characters';
}
}
function countChars3(obj) {
var maxLength = 20;
var strLength = obj.value.length;
var charRemain = (maxLength - strLength);
if (charRemain < 0) {
document.getElementById("charNum3").innerHTML = '<span style="color: red;">You have exceeded the limit of ' + maxLength + ' characters</span>';
} else {
document.getElementById("charNum3").innerHTML = charRemain + ' characters remaining';
}
}
</script>
</head>
<body>
<h1>Live Character Counter using JavaScript</h1>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="div-center">
<h4>Live Characters Count</h4>
<p><textarea name="message" onkeyup="countChars(this);"></textarea></p>
<p id="charNum">0 characters</p>
<h4>Live Characters Count with Max Length</h4>
<p><textarea name="message" onkeyup="countChars2(this);"></textarea></p>
<p id="charNum2">0 characters</p>
<h4>Remaining Characters Count</h4>
<p><textarea name="message" onkeyup="countChars3(this);"></textarea></p>
<p id="charNum3">25 characters remaining</p>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</body>
</html>