How to use LocalStorage on last HTML select value - javascript

How can I set/retrieve the last selected value of a select drop-down with JavaScript? I'm trying to create an onchange function on a select drop-down that that sets the selected option, and then on each page-load, that valued is loaded.
Here is the HTML
<select class="testSelect">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test2">test3</option>
<option value="test2">test4</option>
</select>
I'm having a little trouble with the JavaSCript though.
var select = document.querySelector(".testSelect");
var selectOption = select.options[select.selectedIndex];
var getLast = localStorage.getItem(select, lastSelected);
selectOption = getLast;
select.onchange = function () {
var lastSelected = select.options[select.selectedIndex].value;
localStorage.setItem(select, lastSelected);
}
and here's a fiddle http://jsfiddle.net/5yJNL/1/

The values in your HTML were wrong
<select class="testSelect">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="test4">test4</option>
</select>
Javascript
var select = document.querySelector(".testSelect");
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('select', lastSelected);
}
http://jsfiddle.net/2MPPz/1/

You have at least two problems in your code.
The first one is an scope problem: The lastSelected variable is
local defined in your function. You must define as global variable.
The second one is that the first parameter of setItem & getItem
methods should be a String
So your corrected code looks like:
var lastSelected;
var select = document.querySelector(".testSelect");
var selectOption = select.options[select.selectedIndex];
var getLast = localStorage.getItem('select', lastSelected);
selectOption = getLast;
select.onchange = function () {
lastSelected = select.options[select.selectedIndex].value;
localStorage.setItem('select', lastSelected);
};

Related

Change var value from dropdown in javascript with onchange

I have a dropdown list which looks like this:
<select id="cityID">
<option value="mission">Mission</option>
<option value="bakersfield">Bakersfield</option>
<option value="knoxville">Knoxville</option>
</select>
And my code to get the value is:
var select = document.getElementById('cityID');
var text = select.options[select.selectedIndex].text;
text.innerHTML = cityID.value;
text.onchange = function(e) {
text.innerHTML = e.target.value;
}
The value always chooses the first item. How can I get it to accept the cityID and change the page,
I'm sure its a formatting or typo or wrong value ?
onchange event is trigger from the select element
your text variable seems to be an HTML element because you set its innerHTML property
a select element has a "value" property so you don't need to get it from the selectedIndex of the options.
var select = document.getElementById('cityID');
var textEl = document.getElementById("text")
text.innerHTML = select.value;
select.onchange = function(e) {
textEl.innerHTML = e.target.value;
}
<select id="cityID">
<option value="mission">Mission</option>
<option value="bakersfield">Bakersfield</option>
<option value="knoxville">Knoxville</option>
</select>
<p id="text"></p>
You could achieve this using addEventListener also.
var select = document.getElementById('cityID');
var textEl = document.getElementById("text")
select.addEventListener("change", (e) => {
textEl.innerText = e.target.value;
})

Getting result out of a function into a usable variable?

So I have a simple HTML file that I want to have a select option drop down menu. I have made that when a selection is made the page reloads retaining the option but I can't get the result outside of the function.
<!doctype html>
<html>
<head>
</head><body>
<select id="mySelect" onchange = "getSelectValue();">
<optgroup label="Working">
<option value="rage.zip">Streets of Rage</option>
<option value="quest.zip">Money Quest</option>
</optgroup>
</select>
<div style="width:640px;height:480px;max-width:100%">
<script type="text/javascript">
window.addEventListener('load', function(){
if (localStorage.pick) {
var sel = document.querySelector('#mySelect');
sel.value = localStorage.pick;
}
});
function getSelectValue(){
var sel = document.querySelector('#mySelect');
localStorage.pick = sel.value;
location.reload();
return sel.value;
}
EJS_player = '#game';
EJS_gameUrl = ; // Url to Game rom
EJS_gameID = 4; // ID in your website, required for netplay.
EJS_core = 'segaMD';
</script>
<script src="https://www.emulatorjs.com/loader.js"></script>
</body>
</html>
My issue is the select option result is in the sel.value. I need that value to EJS_gameUrl = .
So if the option 1 is select which is rage.zip then it should be filled in the EJS_gameUrl = "rage.zip"
Im just having trouble with getting that result out of the function . I would prefer to define it to a variable and just add the variable in the EJS_gameUrl = x; or similar. How can I go about this?
See Storing the information you need — Variables, Storage.setItem and Storage.getItem.
Your code should be something along the lines of:
const EJS_player = '#game';
let EJS_gameUrl = ''; // Url to Game rom
const EJS_gameID = 4; // ID in your website, required for netplay.
const EJS_core = 'segaMD';
window.addEventListener('load', function() {
const storedValue = localStorage.getItem('mySelect');
if (storedValue) {
var sel = document.querySelector('#mySelect');
sel.value = storedValue;
EJS_gameUrl = storedValue;
}
});
function getSelectValue() {
localStorage.setItem('mySelect', this.value);
location.reload();
}
console.log(EJS_gameUrl)
<select id="mySelect" onchange="getSelectValue();">
<optgroup label="Working">
<option value="rage.zip">Streets of Rage</option>
<option value="quest.zip">Money Quest</option>
</optgroup>
</select>

Javascript check dropdown value against textbox

I need to check textbox value against dropdown list, and if that value does not exist, add to the list.
I have this script:
<select id="drop" onchange="ChooseContact(this)">
<option value="Volvo Red">Volvo Red</option>
<option value="Mers Blue">Mers Blue</option>
<option value="Ferr red">Ferr red</option>
</select>
function execute(data) {
var txtbox = document.getElementById ("txtServiceReportInspectedBy").value;
if ( document.createElement('option').value != txtbox ) {
var categories = document.getElementById("drop");
var newOption = document.createElement('option');
newOption.innerText = txtbox ;
newOption.setAttribute('value', txtbox );
categories.appendChild(newOption);
}
document.getElementById("drop").value = txtbox ;
}
But the new item is still created in the dropdown list, eventhough such item already there. Thanks.
You are not searching for the text among the options. Here is how you could do that:
add.addEventListener('click', execute);
function execute(data) {
var txtbox = txtServiceReportInspectedBy.value,
optionTexts = Array.from(document.querySelectorAll('#drop>option'),
option => option.value);
if ( !optionTexts.includes(txtbox) ) {
var newOption = document.createElement('option');
newOption.value = newOption.textContent = txtbox ;
drop.appendChild(newOption);
}
drop.value = txtbox;
}
<input id="txtServiceReportInspectedBy"><button id="add">Add</button><br>
<select id="drop">
<option value="Volvo Red">Volvo Red</option>
<option value="Mers Blue">Mers Blue</option>
<option value="Ferr red">Ferr red</option>
</select>
On your "if" sentence you are creating a new element "option" so always is going to be different your "value", so always is going to create a new element inside your "select" tag
You need to iterate for the elements of your "select" tag to find if its value exist or not

How to get different selected values in javascript?

Hello everyone how can I get two values from different select boxes? I get first value in my select box but I can't get the second value from another select box.Here is my javascript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var select = document.forms[0].sel;
var select2=document.forms[0].sel2;
select.onchange = function () {
var value = select.options[select.selectedIndex].value; // to get Value
alert(value);
}
select2.onchange = function () {
var value2 = select2.options[select2.selectedIndex].value; // to get Value
alert(value2);
}
});
</script>
<form>
<SELECT NAME="sel" onChange="split(selected value)">
<OPTION VALUE=1>Milk</option>
<OPTION VALUE=2>tea</option>
<OPTION VALUE=3>water</option>
<OPTION VALUE=4>coffee</option>
</SELECT>
</form>
<form>
<SELECT NAME="sel2" onChange="split(selected value)">
<OPTION VALUE=1>Milk</option>
<OPTION VALUE=2>tea</option>
<OPTION VALUE=3>water</option>
<OPTION VALUE=4>coffee</option>
</SELECT>
</form>
The second select box is in the second form. So:
var select2 = document.forms[1].sel2;
That said, you can actually use jQuery for these things:
// bind a change event handler to the second select
$("select").eq(1).on("change", function() {
alert( $(this).val() );
});
jQuery Tip - Getting Select List Values
var foo = [];
$('#multiple :selected').each(function(i, selected){
foo[i] = $(selected).text();
});
$(document).ready(function () {
$('#sel').change(function(){ $('#sel option:selected').val(); });
give id to your select control
<SELECT id="sel">
with help of jQuery ( i suggest the logic, not the solution )
$(document).on('change', 'select', function(){
var selecetdOption = $(this).val();
alert(selecetdOption );
});​
Working Demo
You have wrong into your javascript because you have put
var select2=document.forms[0].sel2;
try to put
var select2=document.forms[1].sel2;
and it works!

jQuery Filtering

Is there a way to filter a multi-line select box using jQuery?
I'm a new to jQuery and can't seem to figure out the best way to do this.
For example if I have:
<select size="10">
<option>abc</option>
<option>acb</option>
<option>a</option>
<option>bca</option>
<option>bac</option>
<option>cab</option>
<option>cba</option>
...
</select>
I want to filter this list based on a selection drop down with:
<select>
<option value="a">Filter by a</option>
<option value="b">Filter by b</option>
<option value="c">Filter by c</option>
</select>
Something like this might do the trick (assuming you give your 'Filter by...' select an id of filter and the filtered / other select an id of otherOptions):
$(document).ready(function() {
$('#filter').change(function() {
var selectedFilter = $(this).val();
$('#otherOptions option').show().each(function(i) {
var $currentOption = $(this);
if ($currentOption.val().indexOf(selectedFilter) !== 0) {
$currentOption.hide();
}
});
});
});
UPDATE: As #Brian Liang pointed out in the comments, you might have problems setting the <option> tags to display:none. Therefore the following should give you a better cross-browser solution:
$(document).ready(function() {
var allOptions = {};
$('#otherOptions option').each(function(i) {
var $currentOption = $(this);
allOptions[$currentOption.val()] = $currentOption.text();
});
$('#filter').change(function() {
// Reset the filtered select before applying the filter again
setOptions('#otherOptions', allOptions);
var selectedFilter = $(this).val();
var filteredOptions = {};
$('#otherOptions option').each(function(i) {
var $currentOption = $(this);
if ($currentOption.val().indexOf(selectedFilter) === 0) {
filteredOptions[$currentOption.val()] = $currentOption.text();
}
});
setOptions('#otherOptions', filteredOptions);
});
function setOptions(selectId, filteredOptions) {
var $select = $(selectId);
$select.html('');
var options = new Array();
for (var i in filteredOptions) {
options.push('<option value="');
options.push(i);
options.push('">');
options.push(filteredOptions[i]);
options.push('</option>');
}
$select.html(options.join(''));
}
});

Categories

Resources