views:

1576

answers:

4

this can't be too complex but it is baffling me - I would like to pass a variable through a url (www.site.com/index.html?var=whatever.htm) and use the variable within an onclick function so that the onclick button uses the variable as the url to go to..onclick.

I am trying to do this in place of a history button, since the button is within a frame, and clicks to other frames change what the history actually is.

I tried <input value="Go Back" onclick="parent.location(var)" type="button">, but clearly i am missing something on how to get javascript to recognize that variable.

Thanks for any help.

+1  A: 

You need to use document.location.search to access the query string. Then you need to parse that string for the value of your variable.

In you onclick handler, you should set document.location to the value of your variable.

I would suggest adding your click handler when the page loads, as opposed to inlining it with your HTML element.

window.onload = function () {
    document.getElementById("go").onclick = function () {
        var tokens = /\bvar=([^&]+)/.exec(document.location.search);

        if (tokens) {
            document.location = decodeURIComponent(tokens[1]);
        }
    };
};

Edit: For a more generic mechanism for parsing the query string, try this: http://gist.github.com/143101

Ates Goral
A: 

Have you tried something like

<script type="text/javascript">
   var url = "http://gohere.com";
</script>
<input value="Go Back" onclick="document.location(url) type="button" />

You could also have a general function that you call that has the "back" location already set, like

<script type="text/javascript">
  function goBack(url){
    document.location(url);
  }
</script>

In that case you would need to set the url variable somehow. The idea is the same.

Chris Thompson
A: 

Shouldn't you be using

parent.location = var ?

Flavius Stef
A: 

Hi, Accessing Variable From URL: First of all there is no automated way accessing url parameters. So we need to split url into 3 groups.

http://www.someurl.com/doSomeThing?one=1&amp;two=2

we need to get one = 1 and two = 2 parts. We can access this by regular expression.

  var regexString = "[\\?&]var=([^&#]*)";
  var regex = new RegExp( regexString );
  var results = regex.exec( window.location.href );

If the results is an array and first element will be your value.

window.location=results[1];

Regards, Jishnu