I am making a character counter in js but keyup event is not working ???
$(document).ready(function() { function countingCharacter(element, maxCount) { var countLength = $('#' + element).val().length(); alert(countLength); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <textarea onkeyup="countingCharacter("storyOutline",100)" onkeypress="countingCharacter("storyOutline",100);" onkeydown="countingCharacter("storyOutline",100)" id="storyOutline" rows="5" class="form-control" name="labinput7" placeholder="Story Outline" required></textarea>
To avoid any issues related to the functions scope and keep JS code separated from HTML, I'd go with following event binding:
$('#storyOutline').on('keyUp', function() {
var length = $(this).val().length();
alert(length);
});
onkeyup="countingCharacter("storyOutline",100)"
"storyOutline"
will close and open the quotes in onkeyup
You could use single quotes inside the double quotes:
onkeyup="countingCharacter('storyOutline',100)"
You can get textarea length using event.currentTarget.textLength
value
$(document).on("keyup", "#storyOutline", function (e) { console.log(e.currentTarget.textLength); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <textarea id="storyOutline" rows="5" class="form-control" name="labinput7" placeholder="Story Outline" required></textarea>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("input").keyup(function(){
alert("your pressed the key");
});
});
</script>
</head>
<body>
Enter your name: <input type="text">
</body>
</html>
when you keyup on the text field, you'll find an alert message that you have keyed.
Use single quotes to add arguments to the inline JavaScript functions, so:
<textarea onkeyup="countingCharacter('storyOutline')" ... ></textarea>
Instead of
<textarea onkeyup="countingCharacter("storyOutline")" ...></textarea>
But you don't actually need those parameters (you can keep maxCount
inside the function's scope). Then access the target (input box element) with event.target
. Select its input value and its length.
Here's a working code:
function countingCharacter(maxCount) { console.log($(event.target).val().length); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea onkeyup="countingCharacter(100)" onkeypress="countingCharacter(100);" onkeydown="countingCharacter(100)" id="storyOutline" rows="5" class="form-control" name="labinput7" placeholder="Story Outline" required></textarea>
You shouldn't use alert
for debugging, use console.log
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.