Links in <select> dropdown options

前端 未结 6 1963
星月不相逢
星月不相逢 2020-11-27 05:26

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


                        
    
提交评论

  • 2020-11-27 05:55

    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>
    
    0 讨论(0)
  • 2020-11-27 05:56

    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>
    
    0 讨论(0)
  • 2020-11-27 05:57

    Maybe this will help:

    <select onchange="location = this.value;">
     <option value="home.html">Home</option>
     <option value="contact.html">Contact</option>
     <option value="about.html">About</option>
    </select>
    
    0 讨论(0)
  • 2020-11-27 05:59

    This is an old question, I know but for 2019 peeps:

    Like above if you just want to change the URL you can do this:

    <select onChange="window.location.href=this.value">
        <option value="www.google.com">A</option>
        <option value="www.aol.com">B</option>
    </select>
    

    But if you want it to act like an a tag and so you can do "./page", "#bottom" or "?a=567" use window.location.replace()

    <select onChange="window.location.redirect(this.value)">
        <option value="..">back</option>
        <option value="./list">list</option>
        <option value="#bottom">bottom</option>
    </select>
    

    PS. Sorry if the formatting is weird I'm new at Stack Overflows syntax

    0 讨论(0)
  • 2020-11-27 06:02

    ... 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>
    
    0 讨论(0)
  • 提交回复
    热议问题