为了账号安全,请及时绑定邮箱和手机立即绑定

在textarea中计算字符数

在textarea中计算字符数

UYOU 2019-09-19 16:41:17
我想计算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);     }};我的代码有什么问题?这是行不通的!好吧,这是一个新手笔迹,需要帮助。
查看完整描述

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');

  }

});


查看完整回答
反对 回复 2019-09-19
?
撒科打诨

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");

    }

});


查看完整回答
反对 回复 2019-09-19
  • 3 回答
  • 0 关注
  • 581 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信