如何使用户选择的选项输入,在页面刷新后保持不变

时间:2017-03-17 07:14:23

标签: javascript jquery html local-storage

您好我正在尝试使用本地存储来保存选项数据。正如您在代码片段中看到的那样,有给出的选项。假设我选择了不同的选项,例如在Genre I下单击Action等等。但是当我刷新页面时,他们会改回原来的状态。这就是我不想发生的事情。

这是我localStorage的代码

    $('#search').on('click', function(){

    $('input[type="button"]').each(function(){
        var id = $(this).attr('id');
        var value = $(this).val();
       localStorage.setItem(id, value);

    });     
});
.selects-container {
display: inline-block;

}

.selects-container select {
margin: 0;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
width: 130px;
padding-left: 10px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-appearance: none;
box-sizing: border-box;
height: 40px;
color: #a2a2a2;
font-size: .9em;
font-weight: normal;
overflow: hidden;
background-color:#282828;
border: 0;
}

#browsepagebutton {
background: #6ac045;
border-radius: 3px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
display:inline-block;
font-weight: bold;
color: #fff;
height: 42px;
font-size: 16px;
position: relative;
width: 130px;
padding: 7px 0;
margin-top: 20px;
-webkit-transition: all 300ms ease;
-moz-transition: all 300ms ease;
transition: all 300ms ease;
}
<script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id ="searchfield">
 <div id="main-search-fields">
  <div class="selects-container">
  <p>Genre:</p>
  <select name="genre">
  <option value="all">All</option>
  <option value="action">Action</option>
  <option value="adventure">Adventure</option>
  <option value="animation">Animation</option>
</select>
</div>

  <div class="selects-container">
  <p>Rating:</p>
  <select name="rating">
  <option value="0">All</option>
  <option value="9">5</option>
  <option value="8">4</option>
  <option value="7">3</option>
  <option value="6">2</option>
  <option value="5">1</option>
  </select>
  </div>

<div class="selects-container" class="selects-container-last">
<p>Year:</p>
<select name="order_by">
<option value="0">2005</option>
<option value="9">2006</option>
<option value="8">2007</option>
<option value="7">2008</option>
  </select>
</div>
</div>
<input type="button" onclick="saveValues()" id="browsepagebutton"   value="search"  />
</div>
</div>

1 个答案:

答案 0 :(得分:1)

以下代码将获取每个选择的值并进行设置。然后当页面加载时,它将设置值。

$('#browsepagebutton').on('click', function() {

  $('select').each(function() {
    var id = $(this).attr('name');
    var value = $(this).find("option:selected").val();
    console.log("SetItem : " + id + " with value : " + value)
    localStorage.setItem(id, value);

  });
});

$(document).ready(function() {
  $('select').each(function() {
    var id = $(this).attr('name');
    if (localStorage.getItem(id) !== null) {
    var value = localStorage.getItem(id);
    $(this).val(value)
    }

  });
})

Here is a working example of your code