views:

72

answers:

4

I have an html form whose action should be set dynamically throught javascript. How do i do it? Here is what i am trying to do:

<script type="text/javscript">
function get_action() { // inside script tags
 return form_action;
 }
</script>

<form action=get_action()>
...
</form>
A: 
document.forms[0].action="http://..."

...assuming it is the first form on the page.

Diodeus
this might work, but i am still trying to make it work by getting the action string from a function. is there no way to do it like that?
You can write it in an `onsubmit` event handler to make sure it always gets just just before submission. However, in general trying to change a form action from script is a code smell; unless you don't control the server side, it's usually better to make the form accept two+ different submission modes.
bobince
A: 

plain javascript

document.getElementById('form_id').action will retrieve it

document.getElementById('form_id').action = "script.php" will retrieve it

using jQuery..

$("#form_id").attr("action") will retrieve it

$("#form_id").attr("action", "/script.php") will set it
Rabbott
A: 

Do as Rabbott says, or if you refuse jQuery:

<script type="text/javscript">
function get_action() { // inside script tags
  return form_action;
}
</script>

<form action="" onsubmit="this.action=get_action();">
...
</form>
svinto
+2  A: 

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

<script type="text/javscript">
    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/javscript">
    function get_action(form) {
        form.action = form_action;
    }
</script>

<form onsubmit="get_action(this);">
    ...
</form>
BalusC
Although, depending on markup this may not validate, the 'name' attribute is not a valid attribute in XML, its better to use an ID and use the getElementById
Rabbott
@Rabbott: It's HTML, not XML. XHTML is only interesting for server-side HTML-autogenerators like componentbased MVC frameworks.
BalusC