2

I am using the following script:

        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];}
       }
              var id_is = getQueryVariable("id");

document.write(id_is);

       return(false);

}

This script should grab the variable value and display it on screen. It only works if I use getQueryVariable("id"); in the console but using the document.write method it doesn't work. What am I doing wrong?

1
  • What you're doing wrong is using document.write() probably. You'll have to post more about what you're doing and what your page looks like to get more specific help. Commented Feb 7, 2015 at 21:44

3 Answers 3

2

You should call document.write when the page is loaded .

<script type="text/javascript">

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];
          }
   }
}


var id_is = getQueryVariable("id");

window.onload = function(){
  document.write(id_is);
}
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

You can create a function that gets the query parameter from a URL, such as this:

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}

If the query is hello and it equals world, i.e. http://www.website.com/index.html?hello=world. Then you can use getURLParameter('hello') to return it.

Comments

0
var url =window.location.search;

function getQueryParam(name,url) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url)||[,""])[1].replace(/\+/g, '%20'))||null
}

var result=getQueryParam(id,url);
document.write(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.