简体   繁体   中英

How to make a dropdown to select proper selected item?

I have a dropdown like below.

<select name="slt">
 <option value="1">One</option>
 <option value="2">Two</option>
 <option value="3">Three</option>
 <option value="3">Three +</option>
</select>

If I select the option Three + , after some page refresh the selected option became Three because Three and Three + has same value. How to avoid this and make the selected item as Three + after page refresh? Thanks In Advance.

This is because the browser will automatically retain the value. If the value is a duplicate it will pick the first one it finds in the list.

To stop this behaviour, you need to give the Three+ option a unique value , for example:

<option value="3+">Three +</option>

If you cannot change the HTML at all, you will need to store the selected index of the element in localStorage, or a cookie, and set it again on load:

// set onchange
$('select').change(function() {
    localStorage.setItem('sltIndex', $(this).prop("selectedIndex"));
});

// get onload
$(this).prop("selectedIndex", localStorage.getItem('sltIndex') || 0)

The pattern is the same for using a cookie, although the code would need amending.

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