3

I have an input as below and I would like to prefill the value with the value of the query string so that when I access example.com/my.html?phone=12345 the value 1234 should be displayed in the input field. Sorry if my question seems stupid but I have no kind of experience with jquery and javascript

<input type="phone" value="" class="form-control" id="phonenumber"
placeholder="Phone number">
hey
  • 7,299
  • 14
  • 39
  • 57

4 Answers4

8

You can use this script:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

And for setting the values:

$("#phonenumber").val(getParameterByName("phone"));

Reference: How can I get query string values in JavaScript?

Fiddle: http://jsbin.com/hikoyaki/1?phone=12345

Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

Use javascript split()

var test = 'example.com/my.html?phone=12345';
var res = test.split("=");
$("#phonenumber").val(res[1]);

Note: Use this if you have only one query string in url.

Manwal
  • 23,450
  • 12
  • 63
  • 93
1

Here is a Plain javascript way of doing it

CSS-TRICKS

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);
}
saikiran
  • 2,247
  • 5
  • 27
  • 42
-2

Below example may help you

var location = 'example.com/my.html?phone=12345';
var phoneNo = location.split("?phone=")[1];
prakashstar42
  • 677
  • 1
  • 6
  • 16