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>
Check for null before use.
if (localStorage.getItem("select") === null) {
var lastSelected = localStorage.getItem('select');
select.value = lastSelected;
}
I solved this problem by removing the data
in the data-value
attribute. And after, i tried to refresh the page and the value of select is removed. that is not good. the solution is modify the javascript, here is the modification:
Javascript code:
$('#work_area').val(localStorage.workarea);
localStorage.setItem('workarea','');
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;
localStorage.setItem('workarea', lastSelected);
}
html code:
<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>
PHP function code:
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 value='$work_area' >$work_area</option>";
}
}