1

I been through dozens of articles on this on here and on Google but none of them seemed to have worked. I am trying to get parameters from the URL and display them inside an input text field.

This is the code I'm working on:

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

getQueryVariable("inputline1");
getQueryVariable("inputline2");

<input type="text" id="inputline1" value="getQueryVariable('inputline1')" />
<input type="text" id="inputline2" value="getQueryVariable('inputline2')" />

The URL i am trying:

?inputline1=sampletext1&inputline2=sampletext2

My jQuery knowledge is very limited and any help on the right direction on this would be very helpful.

Thanks in advance.

12
  • yes, thanks @baao i have tried that and it didn't worked for me, hence I'm here as mentioned above. Commented Jun 5, 2018 at 8:20
  • 1
    value="getQueryVariable('inputline1')" - don’t expect this to call any function, this is just a static text you have specified as the input field value. Commented Jun 5, 2018 at 8:23
  • @baao “use window.location instead of window.loaction.search - no, don’t. Commented Jun 5, 2018 at 8:32
  • 1
    I've reopened the question. Please update it with the code you are using Commented Jun 5, 2018 at 9:02
  • 1
    Does this help? jsfiddle.net/w1bf9tvz/6 Commented Jun 5, 2018 at 9:15

1 Answer 1

2

Got it finally to work, updated a working script below to help anyone in the future:

function getQueryVariable(variable) {
                var query = window.location.search.substring(1);
                var parms = query.split('&');
                for (var i = 0; i < parms.length; i++) {
                    var pos = parms[i].indexOf('=');
                    if (pos > 0 && variable == parms[i].substring(0, pos)) {
                        return parms[i].substring(pos + 1);;
                    }
                }
                return "";
}

getQueryVariable("inputline1");

$(function () {
        $('#inputline1').val(getQueryVariable('inputline1'))
});

<input type="text" id="inputline1" />

The URL with parameter:

?inputline1=Sample

enter image description here

Sign up to request clarification or add additional context in comments.

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.