skip to Main Content

I want to disable submitting form twice. Users often double click on submit button and then form is submitted twice. I already tried following Javascript, but does not work:

const btn = document.querySelector("#buttonid");
btn.addEventListener("dblclick", (e) => {
  e.preventDefault();
});
const button = document.querySelector("#buttonid");
button.addEventListener("click", (e) => {
  document.getElementById("buttonid").disabled = true;
});
$('#buttonid').prop("disabled", true);
<button ondblclick="this.disabled=true;">submit</button>

2

Answers


  1. You can disable the button on after a single click.

    const button = document.querySelector("#buttonid");
    var clickFunc = ()=> {
      button.disabled = true;
    }
     
    #buttonid{
    padding: 10px 24px;
    border: solid 2px;
    color: green;
    border-radius: 6px;
    font-size: 16px;
    letter-spacing: .7px;
    background-color: #fff;
    cursor: pointer;
    }
    
    #buttonid[disabled]{
    color: #ddd;
    cursor: default;
    }
    <button onclick="clickFunc()" id="buttonid">Submit</button>
    Login or Signup to reply.
  2. Use the onsubmit form event. In this way the button wont get disabled on validation errors, only when submited.

    const myFunction = () => {
      const submitButton = document.getElementById("submitButton");
      submitButton.disabled = true;
    }
    <form onsubmit="myFunction()">
      Enter name: <input type="text">
      <input id="submitButton" type="submit">
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search