How to add additional fields to form before submit?

Spook picture Spook · Jul 23, 2013 · Viewed 199k times · Source

Is there a way to use javascript and JQuery to add some additional fields to be sent from a HTTP form using POST?

I mean:

<form action="somewhere" method="POST" id="form">
  <input type="submit" name="submit" value="Send" />
</form>

<script type="text/javascript">
  $("#form").submit( function(eventObj) {
    // I want to add a field "field" with value "value" here
    // to the POST data

    return true;
  });
</script>

Answer

Suresh Atta picture Suresh Atta · Jul 23, 2013

Yes.You can try with some hidden params.

  $("#form").submit( function(eventObj) {
      $("<input />").attr("type", "hidden")
          .attr("name", "something")
          .attr("value", "something")
          .appendTo("#form");
      return true;
  });