user5920040
user5920040

Reputation: 13

javascript pass a variable in url then select option is selected

I am trying to figure out how to pass a variable assigned to a link on one page and then have it prefill a select option in a form on another page.

Source page link: example.com/page?value=2

Page with form:

<select name="select_name" id="id_name" class="select-success">
<option selected="selected" value=""></option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>

From reading various posts and the code I have to work with not really matching that criteria. I am a bit js illiterate. I cobbled this together on the page with the form:

document.getElementByType(“select").value = location.search.replace('?','');

Not getting any results. The form is being generated in the backend so I cannot add a id/class or anything to the <option>.

Upvotes: 1

Views: 1508

Answers (4)

Rob M.
Rob M.

Reputation: 36511

This will turn the querystring into an key => value object:

var qs = location.search.substr(1).split('&').reduce(function(prev, cur) {
  var split = cur.split('=');
  prev[split[0]] = decodeURIComponent(split[1]);
  return prev;
}, {});

And this will set the selected item:

window.addEventListener('load', function() {
   document.getElementById("id_name").value = qs.value;
});

Upvotes: 1

SteamDev
SteamDev

Reputation: 4404

1.) You aren't properly parsing the search string.

location.search // "?value=2"

2.) .getElementByType() isn't a method

Solution

There are fancier ways of parsing query string values, but this is a 1-line solution that should work for you.

document.getElementById('id_name').value = location.search.replace('?value=','');

Upvotes: 0

Ignacio T&#233;llez
Ignacio T&#233;llez

Reputation: 451

I'm not a Javascript expert, but you can surely use some previously-made solutions to solve your problem.

On this other StackOverflow post you can find how to modify an URL to set a GET parameter, and also check if the parameter already exists.

To change a SELECT value, I recommend you assign an ID to it, and then reference it by ID rather than Type. Something like this:

document.getElementById('id_name').value = window.location.search.replace("?", "");

Hope this helps!

Upvotes: 0

Vinny M
Vinny M

Reputation: 770

I would use local storage to do this. Check out: https://github.com/js-cookie/js-cookie

On the first page simply:

Cookies.set('name', 'value');

On the subsequent page:

Cookies.get('name'); // => Returns 'value'

Upvotes: 0

Related Questions