设置最大单词数HTML文本框 [英] Set maximum number of words HTML textbox

查看:57
本文介绍了设置最大单词数HTML文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个 最大数量 个用户可以在文本框中键入的单词,不是个字符数,但是.
这个有可能?

我做了一些挖掘,发现了如何使用正则表达式获取用户输入的单词数,但是我不确定如何在达到最大值后阻止用户输入更多字母

I want to set a maximum number of words the user can type in a textbox, not the number of character but words.
This is possible?

I did some digging and found out how to get the number of words the user has inputted using regular expressions, but im not sure how to stop the user from entering more letters after reaching the max

var jobValue = document.getElementsById('textBox1').value
var words = jobValue.value.match(/\S+/g).length;
if(words>=2){
   //stop inputs
}

PS.
我想将字数限制为2.

PS.
I want to limit the number of words to 2.

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()" > 

推荐答案

您可以添加事件监听器,然后测试单词数.

You can add an eventlistener, then test the number of words.

  • 查找所有有字数限制的输入
  • 遍历列表中的每个项目
  • 向每个项目添加事件监听器
  • 使用onkeydown
  • 查找输入中的单词数
  • 如果我们已达到最大字数,则不允许再有空格
  • 否则我们可以允许其他字符
  • Find all inputs that have a word limit
  • Iterate through each item in the list
  • Add an event listener to each item
  • Find the number of words in the input with onkeydown
  • If we have reached the max number of words don't allow for any more spaces
  • Otherwise we can allow for other characters

// 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>

这篇关于设置最大单词数HTML文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆