亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在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 關注
  • 643 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號