我有一个这样的按钮:
<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;,但如果用户忘记输入“鸟”的值并按下按钮,用户就不能再按一次。有什么建议吗?
发布于 2020-08-03 19:52:05
这将清除表单,如果用户发送了有效的输入。否则,他们将能够单击,但事件将被阻止。所以在表单生效之前,它不会提交表单。如果你愿意,你可以弹出一条消息。
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>
发布于 2020-08-03 19:54:09
在提交函数中,检查输入字段是否已填写。如果不是,则显示警报。一旦满足此条件,您就可以禁用该按钮。
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')
}
}https://stackoverflow.com/questions/63228754
复制相似问题