我想设置一个最大数量用户可以在文本框中输入的单词数,not字符数但是words.
这个有可能?
我做了一些挖掘,发现如何获取用户使用正则表达式输入的单词数,但我不确定如何阻止用户在达到最大值后输入更多字母
var jobValue = document.getElementsById('textBox1').value
var words = jobValue.value.match(/\S+/g).length;
if(words>=2){
//stop inputs
}
PS.
我想将字数限制为 2。
UPDATE
function wordLimit(){
var jobValue = document.getElementById('wordIntent').value
var words = jobValue.value.split(/\s+/);
var maxWords = 2;
var numWords = words.length;
if(numWords > maxWords){
jobValue.preventDefault();
}
}
<input type="text" id="wordIntent" onkeydown="wordLimit()" >
您可以添加一个事件监听器,然后测试单词数。
- 查找所有有字数限制的输入
- 遍历列表中的每个项目
- 为每个项目添加一个事件监听器
- 查找输入中的单词数
onkeydown
- 如果已达到最大字数,则不允许有更多空格
- 否则我们可以允许其他字符
// Get all inputs that have a word limit
document.querySelectorAll('input[data-max-words]').forEach(input => {
// Remember the word limit for the current input
let maxWords = parseInt(input.getAttribute('data-max-words') || 0)
// Add an eventlistener to test for key inputs
input.addEventListener('keydown', e => {
let target = e.currentTarget
// Split the text in the input and get the current number of words
let words = target.value.split(/\s+/).length
// If the word count is > than the max amount and a space is pressed
// Don't allow for the space to be inserted
if (!target.getAttribute('data-announce'))
// Note: this is a shorthand if statement
// If the first two tests fail allow the key to be inserted
// Otherwise we prevent the default from happening
words >= maxWords && e.keyCode == 32 && e.preventDefault()
else
words >= maxWords && e.keyCode == 32 && (e.preventDefault() || alert('Word Limit Reached'))
})
})
<p><input type="text" data-max-words="2" data-announce="true"></p>
<p><input type="text" data-max-words="3"></p>
<p><input type="text" data-max-words="4"></p>
<p><textarea data-max-words="100" rows="5" style="width:100%" data-announce="true"></textarea></p>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)