I would like to make the submit button disable just after submitting

Viewed 67

I would like to make the SUBMIT-BUTTON disable just after submitting. Here is what I wrote and it doesn't work. Could you please give me a clue what the problem is?

<div>
    <form id="manual_form" action="" method="POST">
        <button id="button" type="submit" name="manual_start">SUBMIT!</button>
    </form>
</div>
<hr>
<script type="text/javascript">
    let manual_form = document.getElementById('manual_form');
    let manual_button = document.getElementById('button');

    manual_form.addEventListener('submit', (evt) => {
        console.log('submitted!');
        manual_button.disabled = true;
    }, false);
</script>
3 Answers

The submit can be disabled using the setAttribute() method by assigning the appropriate disabled attribute. In your case, it will be like this:

...
manual_button.setAttribute('disabled', 'disabled');
...

let manual_form = document.getElementById('manual_form');
    let manual_button = document.getElementById('button');

    manual_form.addEventListener('submit', (evt) => {
        evt.preventDefault();
        console.log('submitted!');
        manual_button.setAttribute('disabled', 'disabled');
    }, false);
<div>
    <form id="manual_form" action="" method="POST">
        <button id="button" type="submit" name="manual_start">SUBMIT!</button>
    </form>
</div>
<hr>

When you click the submit button, the page reloads. That is why you don't see the disabled attribute in action. You can add evt.preventDefault(); in the event Handler to prevent the reloading

let manual_form = document.getElementById('manual_form');
let manual_button = document.getElementById('button');

manual_form.addEventListener('submit', (evt) => {
  evt.preventDefault();
  console.log('submitted!');
  manual_button.disabled = true;
}, false);
<div>
  <form id="manual_form" action="" method="POST">
    <button id="button" type="submit" name="manual_start">SUBMIT!</button>
  </form>
</div>
<hr>

The JavaScript side works it's something about the form... when the page is refreshed it throws an error. Add evt.preventDefault(); inside the event listener function to stop the page from refreshing. The button is disabled.

Related