动态文本区域内单词的字符限制
character limit in a word inside a textarea dynamically
我正在尝试限制一个单词中的字符数。我成功地发现,如果有人输入超过 15 character.i,我现在正在显示一条消息。我想要做的是,如果有人输入超过 15 个字符... java 脚本显示一个警告,然后删除所有字母,留下该单词的前 14 个字符。我试图找到一些有用的功能,但从未找到有用的东西。
我想在用户仍在输入时动态检查字符限制。
我的代码只完成了一半,但有一个缺陷。当计数达到 15 以上时,它会显示消息,它会显示警报。现在用户仍然可以保存一个单词中超过 15 个字符的字符串。希望我向所有人all.thanks 解释了它,对于每个提前付出一些努力的人。
<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>
我正在尝试限制一个单词中的字符数。我成功地发现,如果有人输入超过 15 character.i,我现在正在显示一条消息。我想要做的是,如果有人输入超过 15 个字符... java 脚本显示一个警告,然后删除所有字母,留下该单词的前 14 个字符。我试图找到一些有用的功能,但从未找到有用的东西。 我想在用户仍在输入时动态检查字符限制。 我的代码只完成了一半,但有一个缺陷。当计数达到 15 以上时,它会显示消息,它会显示警报。现在用户仍然可以保存一个单词中超过 15 个字符的字符串。希望我向所有人all.thanks 解释了它,对于每个提前付出一些努力的人。
<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>