3

I want to return a url to form action using javascript function.

I am calling the function like this:

<form action="javascript:getUrl()">

And my function is returning strings of url like this:

function getUrl(){
    if(condition)
        return "this string url";
    else
        return "this string url";
}

When I am doing this, the resultant page simply shows the urls in text format on browser instead of loading them.

I am pretty new to these scripting and web designing stuffs.

tonymarschall
  • 3,862
  • 3
  • 29
  • 52
Manu Arora
  • 47
  • 1
  • 2
  • 5
  • Possible duplicate of [How to set form action through JavaScript?](http://stackoverflow.com/questions/2701041/how-to-set-form-action-through-javascript) – gus27 Feb 08 '17 at 09:07

2 Answers2

0

javascript:getUrl() is not going to be interpreted as JS code, it's just a literally string.

Instead select form element and set its action property:

function getUrl() {
  // ...
}

document.querySelector('form').action = getUrl()

Naturally, use more specific selector for your form, id or class.

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

You can use the id of your form to know the action url.

Javascript :

<script type="text/javascript">
function form_action() { 
  if (document.getElementById("myFormId").action == "url1.html"){
     // do something
  }
  if (document.getElementById("myFormId").action == "url1.html"){
     // do something else 
  }

  // ...
}
</script>

The html form :

<form action="yourUrl" onsubmit="this.action=form_action();" id="myFormId">
...
</form>