Selecting the selected option from the drop-down list selected after changing the page

So, I created my first responsive website, but had problems with the menus on my mobile device. Everything works so that when you use a mobile phone, you can select an option from the drop-down list (HTML below) and it will lead you to the correct page. However, when the page loads by default, the "Home" is returned. This is the first option on the list.

This means that you cannot choose a house when you are on another page. But I need it when the option is selected and a new page is loaded for the selected one and then it will become standard. Therefore, you can return to the main page using the drop-down list.

I have not done this before, so I hope that it will be quite simple!

HTML:

<form id="mobile_nav"> <select id="mobile_menu"> <option value="/">Home</option> <option value="/page 1/">page 1</option> <option value="/page 2/">page 2</option> <option value="/page 3/"page 3</option> <option value="/page 4/"page 4</option> <option value="/page 5/"page 5</option> </select> </form> 

JS:

  jQuery(document).ready(function() { nav(); jQuery("#mobile_menu").val(location.pathname); jQuery("#mobile_menu").change(function() { document.location = jQuery(this).val(); }); 

JS allows the dropdown menu on the mobile device.

Let me know if you need more information and thanks.

+4
source share
4 answers

This can help:

 jQuery(document).ready(function(){ jQuery("#mobile_menu").val(location.pathname) }); 

This will try to set the value of #mobile_menu in the same way as the path path to the location (current URL).

+1
source

You can find out the current URL using document.URL . By comparing this URL with the values ​​in the drop-down list, you can select the appropriate option when loading the page. E.g. You can use a similar approach:

 var currentURL = document.URL; if (currentURL.indexOf("home")) { $("#mobile_nav select").val("home"); } 
0
source

use window.location.href to get the current location and select

  jQuery(document).ready(function(){ jQuery("#mobile_menu").val(window.location.href); }); 
0
source

My knowledge in this area is outdated, but it may lead to some idea (I hope).

 <head> <script> function makeDefault(elm) { elm.options[elm.selectedIndex].selected = 'selected'; alert(elm.innerHTML); } </script> </head> <body> <form id="mobile_nav"> <select id="mobile_menu" onchange="makeDefault(this)"> <option value="/">Home</option> <option value="/page 1/">page 1</option> <option value="/page 2/" selected='selected'>page 2</option> </select> </form> </body> 
0
source

All Articles