简体   繁体   中英

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

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

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'

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!

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=','');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM