hey
hey

Reputation: 7819

How to populate an input with query string value(s) using jQuery?

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">

Upvotes: 4

Views: 9312

Answers (4)

prakashstar42
prakashstar42

Reputation: 687

Below example may help you

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

Upvotes: -2

saikiran
saikiran

Reputation: 2435

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

Upvotes: 1

Manwal
Manwal

Reputation: 23816

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.

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

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

Upvotes: 9

Related Questions