简体   繁体   中英

Onclick button href based on drop-down

Premise:

In this particular example, I am trying to make a selection in a drop-down menu and change the keyword 'something' in the onclick() handler mentioned below with whatever value is associated with the selection made in #panel_link_library . Hope this makes sense?

Code so far:

 var aaa = document.getElementById('panel_link_library') aaa.onchange = function() { document.getElementById("abc").href = this.value } 
 <div class="dropdown-plans"> <select id="panel_link_library" name="p_links"> <option value="/pages/home_up/">Location 1</option> <option value="www.google.com">Location 2</option> <option value="https://321.com">Location 3</option> </select> </div> <div id="abc" class="panel_link" onclick="location.href='something'">Jump to location</div> 

Solution:

Your onclick simply needs to read the value of the selection!

 const navToSelection = _ => { const el = document.getElementById("panel_link_library") const val = el.options[el.selectedIndex].value window.location.href = val // That's it! } 
 <div id="abc" class="panel_link" onclick="navToSelection()">Jump to location</div> 

Explanation:

  • We first fetch the dropdown element by it's id = panel_link_library
  • Then we get that elements selected element, and from that read its value property
  • Use this to then set as the new location for your browser to navigate to

Change the location at the onclick function, then you can go and get the dropbox value and redirect the user.

Hope this is what you were looking for. Happy to explain or help in a better solution if needed.

 var aaa = document.getElementById('panel_link_library'); function goToSomewhere() { window.location.href= aaa.value; } 
 <div class="dropdown-plans"> <select id="panel_link_library" name="p_links"> <option value="/pages/home_up/">Location 1</option> <option value="https://www.google.com">Location 2</option> <option value="https://321.com">Location 3</option> </select> </div> <div id="abc" class="panel_link" onclick="goToSomewhere()">Jump to location</div> 

You're trying to assign an href to a div. assign it to the onclick handler.

var aaa = document.getElementById('panel_link_library');
  aaa.onchange = function (e) {
    console.log(e);
    var abc = document.getElementById("abc");
    abc.addEventListener('click', () => {window.location = e.target.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