Manish Kumar
Manish Kumar

Reputation: 10492

Map forms field with the url parameters

In jquery is it possible to map forms field with the url parameters?

e.g i have url :

www.example.com/search?city=mumbai&countyr=IN

whenever this URL is browse it should set the form field's city , country value with mumbai and IN respectively.

Upvotes: 2

Views: 211

Answers (2)

martynas
martynas

Reputation: 12300

You can retrieve the parameters from the URL this way:

$.urlParam = function(name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) return null;
    else return results[1] || 0;    
} 

var city = $.urlParam('city');

Then set the value of your input:

$("#city").val(city);

Upvotes: 1

Clément Andraud
Clément Andraud

Reputation: 9269

For GET parameters, you can grab them from document.location.search:

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

var $_GET = getQueryParams(document.location.search);

After that, just retrieve your correct GET, and set the value of your input ;)

Upvotes: 0

Related Questions