Links in <select> dropdown options

2019-01-05 03:08发布

Is it possible for each dropdown options to link somewhere when selected without the need for an external button?

<select>
  <option value="x">x</option>
  <option value="y">y</option>
</select>

4条回答
放荡不羁爱自由
2楼-- · 2019-01-05 03:39

You can use the onChange property. Something like:

<select onChange="window.location.href=this.value">
    <option value="www.google.com">A</option>
    <option value="www.aol.com">B</option>
</select>
查看更多
劫难
3楼-- · 2019-01-05 03:40

Add an onchange event handler and set the pages location to the value

<select id="foo">
    <option value="">Pick a site</option>
    <option value="http://www.google.com">x</option>
    <option value="http://www.yahoo.com">y</option>
</select>

<script>
    document.getElementById("foo").onchange = function() {
        if (this.selectedIndex!==0) {
            window.location.href = this.value;
        }        
    };
</script>
查看更多
The star\"
4楼-- · 2019-01-05 03:43

... or if you want / need to keep your option 'value' as it was, just add a new attribute:

<select id="my_selection">
<option value="x" href="/link/to/somewhere">value 1</option>
<option value="y" href="/link/to/somewhere/else">value 2</option>
</select>

<script>
document.getElementById('my_selection').onchange = function() {
    window.location.href = this.children[this.selectedIndex].getAttribute('href');
}
</script>
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-05 03:47

You can use this code:

<select id="menu" name="links" size="1" onchange="window.location.href=this.value;">
    <option value="URL">Book</option>
    <option value="URL">Pen</option>
    <option value="URL">Read</option>
    <option value="URL">Apple</option>
</select>
查看更多
登录 后发表回答