javascript在url中传递变量,然后选择选项

时间:2016-02-12 19:16:04

标签: javascript jquery

我试图找出如何在一个页面上传递分配给链接的变量,然后让它在另一个页面上预先填写表单中的选择选项。

源页面链接: example.com/page?value=2

带表单的页面:

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

从阅读各种帖子和我必须使用的代码并没有真正匹配该标准。我有点文盲。我在页面上用形式拼凑了这个:

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

没有得到任何结果。表单是在后端生成的,因此我无法向<option>添加id / class或任何内容。

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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'

答案 2 :(得分:0)

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!

答案 3 :(得分:0)

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