如何显示文本框剩余的字符?

时间:2018-09-19 14:58:45

标签: javascript

我想在我的代码中实现一个仅允许最多150个字符的简单文本框。这部分相对容易。现在,如何显示文本框中还剩下多少个字符?

示例:

<textarea  maxlength="150" rows="5" cols="50" wrap="hard">
    In 150 characters or less, tell me something about yourself...
</textarea>

2 个答案:

答案 0 :(得分:2)

您可以将input事件附加到textarea上,然后每次用户键入或删除一个字符时,您都可以执行(max-current_characters)操作,并在跨度中显示结果:

var max = 150;
var textarea = document.querySelector('textarea');
var info = document.querySelector('#info');

//Init the count for the first time
info.textContent = max - textarea.value.length;

textarea.addEventListener('input', function() {
  info.textContent = max - this.value.length;
})
<textarea maxlength="150" rows="5" cols="50" wrap="hard">

In 150 characters or less, tell me something about yourself...

</textarea>
<br> Remaining <span id="info"></span> characteres

答案 1 :(得分:0)

获取box值,并从您拥有的最大长度中恢复该值:

 let message = document.getElementById('messageBox').value;
 let value =  150;
 var length = value - message;

根据需要使用length变量。

这是我之前做过的一个示例,甚至可以更改其颜色并使用正则表达式确定是否存在空格:

 // Reads the text area value.
 let message = document.getElementById('messageBox').value;

if((character.length <= 0 || !(/[^\s]/.test(message))) && character.length <= 280){
 // Disables submit button.
 sumbitStatus(true);
 // Sets invisible the message of more than 280 characters.(In case the user select and delete the whole message in one move).
 document.querySelector('.advertisement').style.display =  "none";
 // returns counter to blue color.(In case the user select and delete the whole message in one move).
 document.querySelector('.character').style.color = '#1EAEDB';
 } else if(character.length >= 281){
   // Disables submit button and changes counter to red.
   sumbitStatus(true); 
   document.querySelector('.character').style.color = 'red';
   // Set visible the message of more than 280 characters.
   document.querySelector('.advertisement').style.display = 'block';
  } else{
     // Enables Submit button and returns counter to blue color.
     sumbitStatus(false); 
     if(character.length >= 250){
     document.querySelector('.character').style.color = 'orange';
     // Sets invisible the message of more than 280 characters.
     document.querySelector('.advertisement').style.display = "none";
     }
     else{
     document.querySelector('.character').style.color = '#1EAEDB';
     // Sets invisible the message of more than 280 characters.
     document.querySelector('.advertisement').style.display = "none";
     }
    }  
   }