Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form not submitting after disabling submit button

I have an HTML form that has a submit button. I want this button to be disabled when it is clicked. But I also want the form to get submitted.

I am not using ajax request to submit the form. The PHP script that handles the form takes a long time. So some users just click it after a few seconds and the form gets submitted twice which leads to two rows with the same data in the database.

Here's what I tried so far

<form method="POST" action="xyz.php">
    <input type="text" name="fields[]" />
    <input type="text" name="fields[]" />
    <input type="text" name="fields[]" />
    <input type="text" name="fields[]" />
    <input type="submit" onclick="$(this).attr('disabled', true);" value="Submit" />
</form>

The onclick event on submit button disables the button but it also don't let the form to be submitted. But I want the form to be submitted and also want the button to be disabled.

like image 467
Amarjit Singh Avatar asked Dec 17 '22 21:12

Amarjit Singh


2 Answers

You May try the below code onclick="this.disabled=true;this.form.submit();this.value='Submiting...';"

like image 78
Harat Avatar answered Dec 28 '22 10:12

Harat


If you're using jQuery, then here's a fully-jQuery, unobtrusively handled version which would work.

If you were to give your form an ID, you could make it handle that form specifically - this example will handle all forms on your page.

$(function() {
  $("form").submit(function(event) {
    $(this).find('input[type="submit"]').prop("disabled", true);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="xyz.php">
  <input type="text" name="fields[]" />
  <input type="text" name="fields[]" />
  <input type="text" name="fields[]" />
  <input type="text" name="fields[]" />
  <input type="submit" value="Submit" />
</form>

Note that you should use .prop() rather than .attr() to set properties such as "disabled" (see http://api.jquery.com/attr/).

like image 41
ADyson Avatar answered Dec 28 '22 10:12

ADyson