0

I want to check the URL for a parameter. If this parameter exists, I want to pass it into an input.

The URL is eg. www.xyz.com/?userid=1234

The goal should be:

  1. Check if URL contains parameter "userid="
  2. If yes, set the value as input of a value

My problem is, that I don't know, how to grab the value of the parameter. In my opinion it must be something like "take everything after "userid=" up to the end or an "&" (as possible beginn of new value)".

I think I would do with:

<input type="hidden" name="userid" type="text" value="" />
if(window.location.href.indexOf('userid=') > -1) { ... }
$('input[name=userid]').val('...');

In the end, the input should be have the value "1234" in my example.

Maximilian Neuse
  • 153
  • 1
  • 5
  • 15
  • Try [this answer](https://stackoverflow.com/a/21903119/783014). It should be what you are looking for. – jerkan Jan 09 '19 at 09:36

1 Answers1

1

You can use URLSearchParams interface to grab the query string value using searchParams.get().

var params = new URLSearchParams(url);
console.log(params.get("userid"));

To check if a search parameter exists in the URL, use URLSearchParams.has()

params.has('userid') === true;
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
  • Thank you! I found the full solution here: https://stackoverflow.com/questions/22930667/trying-to-pass-url-parameters-to-input-fields-not-form-fields – Maximilian Neuse Jan 09 '19 at 09:45