一次按下允许按钮

时间:2020-08-03 11:39:48

标签: javascript html

我有一个像这样的按钮:

<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”中输入值并按下按钮,则用户无法再次按下它。有提示吗?

2 个答案:

答案 0 :(得分:0)

如果用户发送了有效的输入,这将清除表格。 否则他们将能够点击,但事件将被阻止。因此它在有效之前不会提交表单。您可以根据需要弹出一条消息。

var btn = document.getElementById('submit')
var colorInput = document.querySelector('input[name=Color]')
var birdInput = document.querySelector('input[name=Bird]')


btn.addEventListener("click", function (e) {
    if(colorInput.value.trim().length === 0 && birdInput.value.trim().length === 0){
        e.preventDefault()
        return
    } else {

        btn.disabled = true;
        colorInput.value = ""
        birdInput.value = ""
        btn.disabled = false;
    }
});
<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>

答案 1 :(得分:0)

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

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')
  }
}