首页 > 解决方案 > 允许按钮被按下一次

问题描述

我有一个这样的按钮:

<fieldset>
     <input type="text" placeholder="Color" name="Color" required>
</fieldset>

<fieldset>
     <input type="text" placeholder="Bird" name="Bird" required>
</fieldset>

<fieldset>
     <button name="submit" type="submit" id="submit">Lagre</button>
</fieldset>

仅当文本字段具有值时才会提交表单。但是如果用户向“提交”按钮发送垃圾邮件并按下它 5 次,表单将被提交 5 次。第一次按下后如何禁用按钮?我知道document.getElementById("submit").disabled = true;,但是如果用户忘记在“Bird”中输入值并按下按钮,用户将无法再次按下它。有小费吗?

标签: javascripthtml

解决方案


在您的提交功能中,检查输入字段是否已填写。如果没有,则显示警报。满足此条件后,您可以禁用该按钮。

JSFiddle:https ://jsfiddle.net/guv12f83/

function submitForm() {
  const color = document.getElementById('colorInput').value.trim();
  const bird = document.getElementById('birdInput').value.trim();
  if (color.length > 0 && bird.length > 0) {
    document.getElementById('submit').disabled = true
    console.log('Enter your code here')
  } else {
    alert('Please fill all fields')
  }
}

推荐阅读