字符限制在文本方面的单词动态



我试图对单词中的字符数量限制。我很成功地发现,如果有人输入更多的15个字符。我现在正在显示一条消息。我想做的是,如果某人输入更多的15个字符... Java脚本显示警报,然后删除所有字母,将所有字母留下该单词中的前14个字符。我试图找到一些有用的功能,但从未找到有用的东西。当用户仍在输入时,我想动态检查字符限制。我的代码一半完成,但有一个缺陷。当计数达到超过15时,它显示了消息,它显示警报。现在,用户仍然可以保存一个单词超过15个字符的字符串。希望我对所有人都解释了这一切。感谢所有人,因为每个人都会提前努力的人。

<textarea id="txt" name="area" onclick="checkcharactercount()"></textarea>

function checkcharactercount(){
  document.body.addEventListener('keyup', function(e) {
      var val = document.getElementById("txt").value;
      var string = val.split(" ");
      for(i=0;i<string.length; i++) {
        len = string[i].length;
        if (len >= 15) {
          alert('you have exceeded the maximum number of charaters in a word!!!');
          break;
        }
      }
  });
}

此功能是否像您想要的一样?

var textArea = document.getElementById('txt');
textArea.addEventListener('keyup', function () {
  var val = textArea.value;
  var words = val.split(' ');
  for (var i = 0; i < words.length; i++) {
    if (words[i].length > 14) {
      // the word is longer than 14 characters, use only the first 14
      words[i] = words[i].slice(0, 14);
    }
  }
  
  // join the words together again and put them into the text area
  textArea.value = words.join(' ');
});
<textarea id="txt" name="area"></textarea>

最新更新