0

Does anybody know a javascript code that will detect the dynamic url of the page (?q=Chicken) and setup a javascript variable called 'query'. I would then like to display the variable as text.

This will all be onload. Can this also be done with a textbox? (Input type text - set text to query)

I cannot use php of asp. Just html and javascript!

JBithell
  • 627
  • 2
  • 11
  • 27

3 Answers3

0

Take a look at this question: Get current URL in web browser

Once you have the full URL, you should be able to parse it using regexs or other any other method that you can think of. Then, you could just set the text of an html element to that query. Or you could create a whole new element and append it somewhere

Community
  • 1
  • 1
taylorc93
  • 3,676
  • 2
  • 20
  • 34
0

You can access the parameters with

document.location.search
Ishank Gupta
  • 1,575
  • 1
  • 14
  • 19
0

Regex can get pretty messy. Check out this Stackoverflow answer instead:

How can I get query string values in JavaScript?

(it links to http://css-tricks.com/snippets/javascript/get-url-variables/ which suggests using this snippet of code:)

function getQueryVariable(variable)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}
  }
  return(false);
}

Usage:

Given this url: http://www.example.com/index.php?id=1&image=awesome.jpg

Calling getQueryVariable("id") - would return "1". Calling getQueryVariable("image") - would return "awesome.jpg".

Community
  • 1
  • 1
willbradley
  • 694
  • 7
  • 11