0

I have a form with two submit buttons as per below.

<form id="choice" name='form' method="POST" action="/">
  <button type="submit" name="vote" id="btnMinus" value="1"></button>
  <button type="submit" name="vote" id="btnPlus" value="2"></button>
</form>

I have this code in order to prevent that the form is not submitted twice. However, it gives a "bad request" error. Seems that it doesn't send the "vote" value. Any ideas?

$('#choice').submit(function(e)
{  
    e.preventDefault(); 
    $('#btnPlus').attr('disabled',true);
    $('#btnMinus').attr('disabled',true);
    this.submit();
});
Community
  • 1
  • 1
  • 3
    It won't send anything because the value of the button is only included in the request when the button triggers the submit. You're cancelling that original button-initiated event and raising a new submit, without the button context. – Rory McCrossan Nov 29 '16 at 16:51
  • 2
    Probably just a typo but you have `$('#btnPlus')` twice. And you should be using `.prop()` instead of `.attr()` – j08691 Nov 29 '16 at 16:52
  • @RoryMcCrossan any suggestions to disable the buttons then? –  Nov 29 '16 at 16:55
  • 1
    An alternative would be to make the buttons standard types, which set the value of a hidden textfield in the form and then call `submit()`. You could also negate the need for the form at all and use AJAX, but that would depend on your implementation. – Rory McCrossan Nov 29 '16 at 16:55
  • 1
    There are a quite a few answers here that might help you: http://stackoverflow.com/questions/2830542/prevent-double-submission-of-forms-in-jquery?rq=1 – pulekies Nov 29 '16 at 16:56

1 Answers1

0

Following @RoryMcCrossan's comment, you can use a hidden input and set it's value once the button is clicked:

$('#choice button').click(function(e) {  
  e.preventDefault();
  $('#vote-el').val($(this).val());
  
  $('#btnMinus').prop('disabled',true);
  $('#btnPlus').prop('disabled',true);
  
  $('#choice').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="choice" name='form' method="POST" action="/">
  <input id="vote-el" type="hidden" name="vote" value="" />
  <button type="submit" name="vote" id="btnMinus" value="1">1</button>
  <button type="submit" name="vote" id="btnPlus" value="2">2</button>
</form>
Dekel
  • 60,707
  • 10
  • 101
  • 129