3 回答
TA贡献2011条经验 获得超2个赞
基于Caterham功能的改进版本:
$('#field').keyup(function () {
var max = 500;
var len = $(this).val().length;
if (len >= max) {
$('#charNum').text(' you have reached the limit');
} else {
var char = max - len;
$('#charNum').text(char + ' characters left');
}
});
TA贡献1934条经验 获得超2个赞
以下是两种keyup不会触发事件的方案:
用户将文本拖入textarea。
用户通过右键单击(上下文菜单)在textarea中复制粘贴文本。
使用HTML5 input事件代替更强大的解决方案:
<textarea maxlength='140'></textarea>
JavaScript(演示):
const textarea = document.querySelector("textarea");
textarea.addEventListener("input", event => {
const target = event.currentTarget;
const maxLength = target.getAttribute("maxlength");
const currentLength = target.value.length;
if (currentLength >= maxLength) {
return console.log("You have reached the maximum number of characters.");
}
console.log(`${maxLength - currentLength} chars left`);
});
如果你绝对想使用jQuery:
$('textarea').on("input", function(){
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if( currentLength >= maxlength ){
console.log("You have reached the maximum number of characters.");
}else{
console.log(maxlength - currentLength + " chars left");
}
});
- 3 回答
- 0 关注
- 616 浏览
添加回答
举报