简体   繁体   English

使用JavaScript在下拉列表中保留选定的值

[英]with JavaScript Keep selected value in dropdown list

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. 例如,如果我选择Male,则下拉列表应将Male作为选定选项,并且只有在我用鼠标单击时才会更改。 How to do this in JavaScript? 如何在JavaScript中执行此操作?

Here's a javascript/jquery way, using localStorage. 这是一个javascript / jquery方式,使用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());
    });
})

HTML pages are stateless - meaning they don't remember state. HTML页面是无状态的 - 这意味着它们不记得状态。 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. 为了做你所描述的,我们通常让服务器端代码输出不同的HTML,具体取决于先前提交的表单的值。

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. 使用URL哈希只有JavaScript方法,但是无论如何,您都需要一些服务器端代码来运行您的网站。

How about if you want to retain the value, when you navigate back to this page through an EDIT button on it successor page. 当您通过其后续页面上的EDIT按钮导航回此页面时,如果要保留该值,该怎么办? Here is my post: Retain dynamically created DropDown list's selected value on event window.history.back()- JavaScript 这是我的帖子: 在事件window.history.back() - JavaScript上保留动态创建的DropDown列表的选定值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM