jQuery Writing textarea Input Word Limit Code
- 2021-08-05 08:51:59
- OfStack
In this paper, we share the specific code of jQuery textarea input word limit for your reference. The specific contents are as follows
// First judge whether the browser is evil or not IE
var bind_name = 'input';// Default event
if (navigator.userAgent.indexOf("MSIE") != -1) {
bind_name = 'propertychange';// Shameless IE Exclusive events
}
var maxlength = 10;// Limit the number of input words
$('#Comment').bind(bind_name, function () {// To textarea Binding event
var strlen = $(this).val().replace(/[^\x00-\xff]/g, "aa").length;// Read the conversion to get the length, and convert Chinese into 2 Length, English spaces ignore calculation 1 Length of
$('#aviableCount').text(function () {//1 A span Show how long the input is now
if (Math.ceil(strlen / 2) > maxlength) {// Exceeds the limited length, only the maximum number is displayed
return maxlength;
}
else {
return Math.ceil(strlen / 2);// Why divide by 2 Well, because the Chinese used to calculate two lengths, here we have to turn back. 0.5 Chinese length calculation of 1 Chinese length
}
});
if (strlen > maxlength * 2) {// If the input exceeds the maximum length, intercept it
for (i = 1; i > 0; i++) {
$(this).val($(this).val().substr(0, $(this).val().length - 1));
if ($(this).val().replace(/[^\x00-\xff]/g, "aa").length <= maxlength * 2) {
break;
}
}
}
})
</script>