Saving dropdown menu selection in a cookie?

后端 未结 3 1628
轻奢々
轻奢々 2020-12-31 11:26

I\'ve seen this posted a few times, but I wasn\'t able to get the code working at all. I need help making this drop down menu save its settings to a cookie, so when the user

3条回答
  •  礼貌的吻别
    2020-12-31 12:15

    Note: This answers adds to Josh Mein's answer. Feel free to merge it.

    We can get the cookie using this function, shamelessly stolen from this question.

    function readCookie(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
      }
      return null;
    }
    

    Then we need to select the value when the page loads. The following code will accomplish just that.

    document.addEventListener('DOMContentLoaded', function() {
      var themeSelect = document.getElementById('ThemeSelect');
      var selectedTheme = readCookie('theme');
    
      if (selectedTheme) {
        themeSelect.value = selectedTheme;
      }
    });
    

提交回复
热议问题