允许按下一次按钮



我有一个这样的按钮:

<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"然后按下按钮,用户就不能再按了。有什么建议吗?

在提交函数中,检查输入字段是否已填充。如果没有,则显示警报。一旦满足此条件,就可以禁用该按钮。

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

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

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>

最新更新