waspinator waspinator - 7 months ago 9
Javascript Question

Find all submit buttons of submitted form

I'm trying to disable all submit type elements of a form once it's submitted, to avoid double clicking. But I only want the buttons within the submitted form to be disabled.

For example when clicking the

Submit
button, only the
Submit
button and the
Another submit to disable (same form)
should be disabled. The other submit elements should remain as they were.

The code below disables all submit elements.



$(document).on('submit', function (event) {
event.preventDefault();

var submit_button = $(':submit');
submit_button.prop('disabled', true);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="submit">Not part of submitted form (leave enabled)</button>
<form>
<input type="text">
<button type="submit">Part of another Form (leave enabled)</button>
</form>

<form>
<input type="text">
<button type="submit">Submit</button>
<button type="submit">Another submit to disable (same form)</button>
</form>




Answer

Well, event.target will refer to the submited form, so you can find all submit buttons inside that form using the :submit selector:

$(document).on('submit', function (event) {
    event.preventDefault();              
    $(':submit',event.target).prop('disabled', true);

});

Check the below snippet example

$(document).on('submit', function(event) {
  event.preventDefault();
  $(':submit', event.target).prop('disabled', true);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit">Not part of submitted form (leave enabled)</button>
<form>
  <input type="text">
  <button type="submit">Part of another Form (leave enabled)</button>
</form>

<form>
  <input type="text">
  <button type="submit">Submit</button>
  <button type="submit">Another submit to disable (same form)</button>
</form>