Skip to content

Instantly share code, notes, and snippets.

@codingwithsara

codingwithsara/index.html Secret

Created Sep 21, 2020
Embed
What would you like to do?
【jQuery】How to Count Up and Down Characters in Textarea
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Text Counter</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
.container {
width: 500px;
margin-top: 100px;
font-size: 18px;
}
#count1, #count2 {
color: grey;
}
</style>
</head>
<body>
<div class="container">
<form>
<div class="form-group">
<label>Count Up</label>
<textarea id="countUp" class="form-control" rows="5"></textarea>
<span id="count1" class="float-right">0</span>
</div>
<div class="form-group">
<label>Count Down</label>
<textarea id="countDown" class="form-control" rows="5"></textarea>
<span id="count2" class="float-right">30</span>
</div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function(){
$('#countUp').keyup(function(){
$('#count1').text($(this).val().length);
});
$('#countDown').keyup(function(){
var remain = 30 - $(this).val().length;
$('#count2').text(remain);
if (remain < 0) {
$('#count2').css('color', 'red');
} else {
$('#count2').css('color', 'grey');
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.