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>
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With