this line needs to be changed
var tam = $(this).val().length;
See Demo
Domanda
in my project have a jQuery Mobile textarea called "topic" on one page
I have this script I am using to count the characters entered in the textarea, but this script just gives me a result on the first keystroke. the other does not.
$(document).delegate("#topicDialog", "pageinit", function() {
$("#topic").keyup(function(e) {
var tam = $(this).length;
if (tam <= 61700){
$("#maxCarac").html(tam +" typed characters. The maximum allowed is 61700");
} else {
alert("You have reached the maximum text size.\nPlease break your text into more than one topic.");
$("#topic").val($("#topic").substring(61700));
}
});
});
What can be happening?
Soluzione 2
Altri suggerimenti
you need to use val().length
check the update fiddle here
$("#topic").keyup(function(e) {
var tam = parseInt($(this).val().length);
if (tam <= 61700){
$("#maxCarac").html(tam +" typed characters. The maximum allowed is 61700");
} else {
alert("You have reached the maximum text size.\nPlease break your text into more than one topic.");
$("#topic").val($("#topic").substring(61700));
}
});
You are retrieving incorrectly the length of the user input. Use this:
var tam = $(this).val().length;
Here a working demo.