with JavaScript Keep selected value in dropdown li

2019-08-10 11:11发布

I have the following drop down list:

Gender<select name="gender"  id="gender"> 
  <option value=" "> EMPTY </option> 
  <option value="Male">Male</option> 
  <option value="Female">Female</option> 
</select>

If I choose one of the options, it should stay selected as a primary option even if I renew the page. For example, if I choose Male, the dropdown list should keep Male as a selected option and this should only change when I click on it with the mouse. How to do this in JavaScript?

3条回答
贼婆χ
2楼-- · 2019-08-10 11:53

HTML pages are stateless - meaning they don't remember state. In order to do what you describe we usually have the server-side code output different HTML depending on the values of the previously-submitted form.

There are JavaScript-only ways to to this using a URL hash, but you're going to need some server-side code to run your web site regardless.

查看更多
Evening l夕情丶
3楼-- · 2019-08-10 12:02

Here's a javascript/jquery way, using localStorage. If you're going to do this in a lot of places there are probably ways to optimize this code.

$(function() {
    var genderValue = localStorage.getItem("genderValue");
    if(genderValue != null) {
        $("select[name=gender]").val(genderValue);
    }

    $("select[name=gender]").on("change", function() {
        localStorage.setItem("genderValue", $(this).val());
    });
})
查看更多
我命由我不由天
4楼-- · 2019-08-10 12:12

How about if you want to retain the value, when you navigate back to this page through an EDIT button on it successor page. Here is my post: Retain dynamically created DropDown list's selected value on event window.history.back()- JavaScript

查看更多
登录 后发表回答