Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Dynamically build form action on submit?

Tags:

jquery

I'm trying to have the action of a HTML form built when the user clicks the submit button.

So the user fills in a form, clicks submit, then the action gets built then it actually gets submitted. The reason being is because the form has a load of options on it which will be passed to a script.

How would I go about doing this with Jquery?

like image 300
Probocop Avatar asked Apr 20 '10 13:04

Probocop


People also ask

How to Change form action dynamically using jQuery?

To do the same using jQuery would be: $(function(){ $('IdOfTheForm'). submit(function(){ this. action = 'the dynamic action'; return true; }); });

How do you dynamically submit a form?

Answer: Use the jQuery submit() Method You can use the submit() method to submit an HTML form (i.e. ) using jQuery. The jQuery code in the following example will submit the form on click of the button (i.e. the element) which has the type attribute set to button (i.e. type=”button” ).

How do I create a dynamic form?

The task is to create an HTML form dynamically with the help of JavaScript. There are two approaches that are discussed below. Approach 1: Use document. createElement() to create the new elements and use setAttribute() method to set the attributes of elements.


3 Answers

Untested, but this should at least get you on your way:

$('#myForm').submit(function (event)
{
    var action = '';
    // compute action here...
    $(this).attr('action', action);
});
like image 138
Matt Ball Avatar answered Oct 27 '22 01:10

Matt Ball


Use jQuery submit event:

$(document).ready(function() {
  $('#yourFormId').submit(function() {
    $(this).attr('action', 'dynamicallyBuildAction'); 
    return false;
  });
});
like image 45
Jarek Avatar answered Oct 27 '22 00:10

Jarek


The plain Javascript solution would have a function:

function changeAction() {
  this.action = 'the dynamic action';
  return true;
}

In the form you would set the onsubmit event:

<form ... onsubmit="return changeAction();">

To do the same using jQuery would be:

$(function(){
  $('IdOfTheForm').submit(function(){
    this.action = 'the dynamic action';
    return true;
  });
});
like image 1
Guffa Avatar answered Oct 27 '22 02:10

Guffa