简体   繁体   中英

How to return a url to form action using a javascript function

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.

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM