在输入最大字数之前,如何禁用显示按钮

问题描述 投票:0回答:1

我正在学习如何编写代码,对javascript的了解很少,因此遇到了一些挑战,将感谢社区的任何帮助。我有一个输入表格,想禁用我的提交按钮,直到输入最大单词。我的代码为:

<script>
// Get reference to textbox
var input = document.getElementById("words");

// Add event handler for event that can be cancelled and prevent excessive data
// from ever getting into the textbox
input.addEventListener("keypress", function(evt){

// Get value of textbox and split into array where there is one or more continous spaces
var words = this.value.split(/\s+/);

// Get # of words in array
var numWords = words.length;

var maxWords = 8;


// If we are at the limit and the key pressed wasn't BACKSPACE or DELETE,
// don't allow any more input
if(numWords > maxWords){
    evt.preventDefault(); // Cancel event
}
</script>
<form action="" method="post "id="myform">
  <div class="form-group">
    <input id="words"  data-max-words="8" data-announce="true" class="words-data-form-control" type="text" name="wordlist" wordlistlength="8"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" required />
  </div>
  <div class="feedback-container">
    <div class="feedback" style="display: none;"></div>
  </div>
  <div class="form-group">
    <button class="btn btn-primary text-capitalize float-right" id="submit" type="submit" style="color: rgb(255,255,255);background-color: rgb(12, 108, 242);" disabled>
      <strong>submit</strong>
    </button>
  </div>
</form>
javascript html forms button
1个回答
0
投票

使用标志,是isWordCountLimitReached的全局变量。保持其默认值false,并在达到限制时将其设置为true。

if(numWords > maxWords){

    evt.preventDefault(); // Cancel event
    isWordCountLimitReached = true
}

现在单击提交,如果此变量为true,则执行。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.