简体   繁体   中英

How to make dropdown selected if URL matched with value?

I'm trying to make a selection in the select box based on the URL. The urls are tied to the value attribute of option . How can I do this in jQuery?

 <select> <option value="http://name.com/">All</option> <option value="http://name.com/category/electronics">Electronics</option> <option value="http://name.com/category/books">Books</option> <option value="http://name.com/category/furniture">Furniture</option> <option value="http://name.com/category/kitchen">kitchen</option> <option value="http://name.com/category/homeware">Homeware</option> <option value="http://name.com/category/outdoors">Outdoors</option> </select>

Maybe you want to bind the dropdown from the web URL. So you can add the id to your <select> tag like "drpCategory". Now you need to add below script for auto-selection of your dropdown.

$(function(){
   $("#drpCategory").val(window.location.href);
});

Put this code immediately after your <select> block:

<script>
$('select').last().val(location.href)
</script>

$('select').last() is jQuery's way to select the preceeding <select> element in the document. .val(value) is jQuery's way of changing the selection to the option with the specified value. By passing location.href to.val() you are telling it to select the option whose value contains the full URL of the current page.

At first, get the pathname from the URL you're currently in. You can do this with this function: window.location.pathname . Then in javascript code check if your pathname matches any of the options value and if it does then add selected attribute on that option.

If you just need to select an option on page load then the following should do it.

$(function(){
   $( "select").val(window.location);
))

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