在textarea中计算字符数

我想计算textarea中的字符,所以我只是做了:


<textarea id="field" onkeyup="countChar(this)"></textarea>


function countChar(val){

     var len = val.value.length;

     if (len >= 500) {

              val.value = val.value.substring(0, 500);

     } else {

              $('#charNum').text(500 - len);

     }

};

我的代码有什么问题?这是行不通的!好吧,这是一个新手笔迹,需要帮助。


UYOU
浏览 617回答 3
3回答

森林海

基于Caterham功能的改进版本:$('#field').keyup(function () {&nbsp; var max = 500;&nbsp; var len = $(this).val().length;&nbsp; if (len >= max) {&nbsp; &nbsp; $('#charNum').text(' you have reached the limit');&nbsp; } else {&nbsp; &nbsp; var char = max - len;&nbsp; &nbsp; $('#charNum').text(char + ' characters left');&nbsp; }});

撒科打诨

以下是两种keyup不会触发事件的方案:用户将文本拖入textarea。用户通过右键单击(上下文菜单)在textarea中复制粘贴文本。使用HTML5 input事件代替更强大的解决方案:<textarea maxlength='140'></textarea>JavaScript(演示):const textarea = document.querySelector("textarea");textarea.addEventListener("input", event => {&nbsp; &nbsp; const target = event.currentTarget;&nbsp; &nbsp; const maxLength = target.getAttribute("maxlength");&nbsp; &nbsp; const currentLength = target.value.length;&nbsp; &nbsp; if (currentLength >= maxLength) {&nbsp; &nbsp; &nbsp; &nbsp; return console.log("You have reached the maximum number of characters.");&nbsp; &nbsp; }&nbsp; &nbsp; console.log(`${maxLength - currentLength} chars left`);});如果你绝对想使用jQuery:$('textarea').on("input", function(){&nbsp; &nbsp; var maxlength = $(this).attr("maxlength");&nbsp; &nbsp; var currentLength = $(this).val().length;&nbsp; &nbsp; if( currentLength >= maxlength ){&nbsp; &nbsp; &nbsp; &nbsp; console.log("You have reached the maximum number of characters.");&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; console.log(maxlength - currentLength + " chars left");&nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JQuery