首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >允许按一次按钮

允许按一次按钮
EN

Stack Overflow用户
提问于 2020-08-03 19:39:49
回答 2查看 40关注 0票数 0

我有一个这样的按钮:

代码语言:javascript
复制
<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;,但如果用户忘记输入“鸟”的值并按下按钮,用户就不能再按一次。有什么建议吗?

EN

回答 2

Stack Overflow用户

发布于 2020-08-03 19:52:05

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

代码语言:javascript
复制
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;
    }
});
代码语言:javascript
复制
<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>

票数 0
EN

Stack Overflow用户

发布于 2020-08-03 19:54:09

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

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

代码语言:javascript
复制
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')
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63228754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档