doujianqin5172
2018-01-29 06:27
浏览 188
已采纳

如何使用localStorage获取所选select的值

I'm trying to get the value of selected select using localStorage.getItem() but it gives me an error.

Here is my select:

            <div class="field">
                <label>Work Area</label>
              <select class="ui fluid dropdown work_area" id="work_area" name="work_area">
                  <option selected value="">Select Work Area.</option>
                  <?php selectWorkArea(); ?>
              </select>

            </div>

Here is my PHP function

 function selectWorkArea(){
    $conn = New Connection;
    $sql = "SELECT DISTINCT work_area FROM machine ORDER BY work_area ASC";
    $qry = $conn->select($sql,NULL,'0129180857');
    while($row= $qry->fetch(PDO::FETCH_OBJ)){
        $work_area = $row->work_area;
        echo "<option data-value='$work_area' >$work_area</option>";
    }

 }

here is my Javascript

 var select = document.querySelector(".work_area");
      var selectOption = select.options[select.selectedIndex];
      var lastSelected = localStorage.getItem('select');
      if(lastSelected) {
          select.value = lastSelected; 
      }
      select.onchange = function () {
        lastSelected = select.options[select.selectedIndex].value;
        console.log(lastSelected);
        localStorage.setItem('workarea', lastSelected);

     }

And i got this error: Error image click here

But when i tried to change my select into this it works totally fine

        <div class="field">
                <label>Work Area</label>
                <select class="ui fluid dropdown work_area" id="work_area" name="work_area">
                  <option selected value="">Select Work Area.</option>
                  <option  data-value="1">1</option>
                  <option data-value="2">2</option>
                </select>
        </div>

click here to see the image

2条回答 默认 最新

相关推荐 更多相似问题