勾选所选的选项元素

时间:2014-11-26 15:09:08

标签: html

这可能是一个非常基本的问题,但我似乎无法弄明白。 在下面的代码中,您可以看到我有一个select-option块。它工作正常。唯一的问题是当我选择其中一个选项(并重定向到相应的页面)时,勾选保持在select-option功能的默认值(“Sort ...”) 。

 <select name="sort" onchange="location = this.options[this.selectedIndex].value;">  
    <option value="">Sort...</option>
    <option value="index.php?ascending=true">Preis aufsteigend</option>
    <option value="index.php?descending=true">Preis absteigend</option>
   </select>

当用户选择“Preis aufsteigend”时,我希望勾选显示在字段中的相应选项中...

有人可以帮忙吗? 提前谢谢!

1 个答案:

答案 0 :(得分:1)

您需要撤销onchange功能。在页面加载时查找您设置的url变量,然后选择适当的选项。

脚本

var sel = document.getElementById('sort');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {
    if(window.location.search.indexOf(opt.value.split('?')[1]) > -1 ) {
        sel.selectedIndex = j;
        break;
    }
}

HTML

<select id="sort" name="sort" onchange="location = this.options[this.selectedIndex].value;">  
    <option value="">Sort...</option>
    <option value="index.php?ascending=true">Preis aufsteigend</option>
    <option value="index.php?descending=true">Preis absteigend</option>
</select>

http://jsfiddle.net/t95wqm48/