Ojibix Creatives
Ojibix Creatives

Reputation: 117

How to pass different hidden input fields based on the clicked submit button

I have two hidden input fields with the same name but with different id. I want to pass it via an action based on different submit button. When I click on the 'normal' process button it should pass the #normalfee hidden field value, and when clicking on 'urgent' it should pass #urgentfee value.

<form name="home" action="#" method="post">
  <input type="hidden" name="fee" id="normalfee" value="49">
  <input type="hidden" name="fee" id="urgentfee" value="99">
  <input type="submit" name="Normal Process">
  <input type="submit" name="urgent process">
</form>

Upvotes: 1

Views: 2049

Answers (2)

Kieran Devlin
Kieran Devlin

Reputation: 1433

I would use a radio button to select the state of the process and then infer the amount on the receiving end. That way users can't modify the value and you only have one button to submit the form while still having multiple options to choose from.

<form name="home" action="#" method="post">
  Fee type:<br>
  <input type="radio" name="fee" value="normalfee">Normal<br>
  <input type="radio" name="fee" value="ugrentfee">Urgent<br>
  <input type="submit" name="Process">
</form>

Upvotes: 1

Mamun
Mamun

Reputation: 68933

According to Form Controls

When a form is submitted for processing, some controls have their name paired with their current value and these pairs are submitted with the form.

You can check the attribute value on button click to remove the name attribute which will ultimately prevents the value from submitting:

$('input[type=submit]').click(function(){
  $('#normalfee, #urgentfee').attr('name', 'fee');
  if($(this).attr('name') == 'Normal Process'){
    $('#urgentfee').removeAttr('name');
    $('#urgentfee').attr('disabled', 'disabled');
  }
  else{
    $('#normalfee').removeAttr('name');
    $('#normalfee').attr('disabled', 'disabled');
  }
  var passVal = $('form').serialize();
  alert(passVal);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="home" action="#" method="post">
  <input type="hidden" name="fee" id="normalfee" value="49">
  <input type="hidden" name="fee" id="urgentfee" value="99">
  <input type="submit" name="Normal Process">
  <input type="submit" name="urgent process">
</form>

Upvotes: 0

Related Questions