Reputation: 4264
I have the below code which I have based off this link
<select name="myselect" class="myselectClass" id="myselectID">
<option data-value='{"comporder":"0"}' value="myval0">test 0</option>
<option data-value='{"comporder":"1"}' value="myval1">test 1</option>
<option data-value='{"comporder":"2"}' value="myval2">test 2</option>
</select>
<br>
<input type="text" id="myinput" name="webStorageInput" />
<input type="submit" id="mysave" value="Save" />
<script type="text/javascript">
var storedText = localStorage.getItem('webStorageTestInput');
var inputBox = document.getElementById("myinput");
var saveBtn = document.getElementById("mysave");
alert(storedText);
saveBtn.onclick = function(){
var valueToSave =inputBox.value.replace(/<\/?[^>]+>/gi, '');
localStorage.setItem('webStorageTestInput',valueToSave);
};
</script>
See my Fiddle
I can store a value I input into local storage through an input field however I want the value I store to use the last option the user selected in my , eg if they selected test 1 their value would be 1.
I thought this was the best way to do this (using data-value) but it is not required I just don't want it to use the options value .
Another approach I tried was to just get the index of the option.
<select name="mySelect" class="myselectClass" id="mySelect">
<option value="myval0">test 0</option>
<option value="myval1">test 1</option>
<option value="myval2">test 2</option>
</select>
<br>
<input type="submit" id="mysave" value="Save" />
<script>
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
var saveBtn = document.getElementById("mysave");
saveBtn.onclick = function(){
alert("Index: " + y[x].index + " is " + y[x].text);
};
</script>
But if I do this I get the below alert each time no matter what I click.
Index: 0 is test 0
Upvotes: 0
Views: 2914