Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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">
like image 955
hey Avatar asked Oct 29 '25 14:10

hey


1 Answers

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

like image 161
Praveen Kumar Purushothaman Avatar answered Nov 01 '25 05:11

Praveen Kumar Purushothaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!