Arturo Arturo - 6 days ago 9
jQuery Question

Form with two submit buttons

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();
});

Answer

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>

Comments