Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the form action through JavaScript?

I have an HTML form whose action should be set dynamically through JavaScript. How do I do it?

Here is what I am trying to achieve:

<script type="text/javascript">     function get_action() { // Inside script tags         return form_action;     } </script>  <form action=get_action()>     ... </form> 
like image 918
umar Avatar asked Apr 23 '10 18:04

umar


People also ask

Can form action JavaScript?

In an HTML form, the action attribute is used to indicate where the form's data is sent to when it is submitted. The value of this can be set when the form is created, but at times you might want to set it dynamically.

How you can submit a form using JavaScript?

In javascript onclick event , you can use form. submit() method to submit form. You can perform submit action by, submit button, by clicking on hyperlink, button and image tag etc. You can also perform javascript form submission by form attributes like id, name, class, tag name as well.

Can form action call JavaScript function?

To call and run a JavaScript function from an HTML form submit event, you need to assign the function that you want to run to the onsubmit event attribute. By assigning the test() function to the onsubmit attribute, the test() function will be called every time the form is submitted.


1 Answers

You cannot invoke JavaScript functions in standard HTML attributes other than onXXX. Just assign it during window onload.

<script type="text/javascript">     window.onload = function() {         document.myform.action = get_action();     }      function get_action() {         return form_action;     } </script>  <form name="myform">     ... </form> 

You see that I've given the form a name, so that it's easily accessible in document.

Alternatively, you can also do it during submit event:

<script type="text/javascript">     function get_action(form) {         form.action = form_action;     } </script>  <form onsubmit="get_action(this);">     ... </form> 
like image 129
BalusC Avatar answered Sep 29 '22 11:09

BalusC