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 關注
- 643 瀏覽
添加回答
舉報