简体   繁体   中英

disable click button on submit

I try to update this jquery script in pure js (with bootstrap 5). The goal is to not allow someone to click twice on the payment button. Sorry I am not very strong in js. My goal is to have the same reaction that the jquery script.

I tried to follow the process on this page: Disabling a button in vanilla JavaScript and in jQuery

Thank you

My current script

<form name="checkout_confirmation" action="http://............/Process" method="post" id="checkout_confirmation" role="form" onsubmit="return checkCheckBox(this)"><section class="checkout_confirmation" id="checkout_confirmation">
div class="text-end" id="process_button" class="processButton">
<button type="submit" data-button="payNow" class="btn btn-success">Confirmer la commande avec paiement</button>    </div>
  </div>
</form>



<script>
  $('form[name="checkout_confirmation"]').submit(function() {
    $('form[name="checkout_confirmation"] button[data-button="payNow"]').html('Confirm the payment').prop('disabled', true);
  });
</script>

Now the script update

<script>
    var button = document.getElementById('checkout_confirmation');

    button.addEventListener('submit', function() {
        alert('Confirm the payment');
    });

    button.disabled = false;
    button.click(); // No output
    button.prop("disabled", true);
</script>

setAttribute can be used in JavaScript to set the attribute of the button as disabled .

Element.setAttribute("disabled", true);

This can be used to disabled the button.

So when someone clicked on the submit button, you can disable the button till the data is processed.

Check the below demo code:

 const btn = document.getElementById("submit-data"); btn.addEventListener("click", submitForm); function submitForm(){ btn.setAttribute("disabled", true); btn.innerText = "Submitting.."; let userName = document.getElementById("user-name").value; console.log("Name: ", userName); setTimeout(() => { btn.removeAttribute("disabled"); btn.innerText = "Submit"; }, 3000); }
 <form type="POST"> <label for="user-name">Full Name</label> <input type="text" id="user-name" placeholder="Your Full Name" /> <br /><br /><br /> <button id="submit-data">Submit</button> </form>

You have two problems:

  • Submit events fire on form elements, not button elements.
  • getElementById gets an element by its id and neither your button nor your form has an id. (See this question ).

Could you not use e.preventDefault() to stop the default behaviour of the button being pressed?

More can be read here: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM