I have a normal select menu and a selectmenu with attribute multiple=yes
. How can I store the values of this second select menu, when the user selects more than one option? The code works if the user chooses only one option, but it doesn't store anything at all, when 2 or more options are selected. My code is:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://github.com/yckart/jquery.storage.js"></script>
<meta charset="utf-8">
<title>test</title>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
var item1 = $("#sel option:selected").text();
var item2 = $("#sel2 option:selected").text();
sessionStorage.setItem("sele", item1);
sessionStorage.setItem("sele2", item2);
});
var ty = sessionStorage.getItem("sele");
var ty2 = sessionStorage.getItem("sele2");
if(ty){
//Set the value of select from sessionStorage
$('#sel option').filter(function () { return $(this).html() == ty; }).prop('selected', true);
$('#sel2 option').filter(function () { return $(this).html() == ty2; }).prop('selected', true);
}
});
</script>
<script type="text/javascript">
$(function () {
$("#btn2").click(function () {
sessionStorage.removeItem("sele");
sessionStorage.removeItem("sele2");
});
});
</script>
</head>
<body>
<section>
<article>
<select id="sel">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
<br />
</article>
</section>
<section>
<article>
<select id="sel2" multiple="yes">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
<br />
<input type="button" value="Store" id="btn" /><br> <input type="button" value="Clear" id="btn2" />
</article>
</section>
</body>
</html>
Select multiple return an array, and you cant store an array in sessionStorage, but you could store the array as a string concatenated by separator then when you read it split the string you get using this separator like :
$(function () {
var ty = sessionStorage.getItem("sele");
var ty2 = sessionStorage.getItem("sele2");
if(ty){
//Set the value of select from sessionStorage
$('#sel option').filter(function () {
return $(this).text() == ty;
}).prop('selected', true);
$('#sel2 option').filter(function () {
return $.inArray( $(this).text(), ty2.split('-'))>-1;
}).prop('selected', true);
}
$("#btn").click(function () {
var item1 = $("#sel option:selected").text();
var item2 = [];
$("#sel2 option:selected").each(function(){
item2.push( $(this).text() );
});
sessionStorage.setItem("sele", item1);
sessionStorage.setItem("sele2", item2.join('-'));
});
$("#btn2").click(function () {
sessionStorage.removeItem("sele");
sessionStorage.removeItem("sele2");
});
});
NOTE : It's better to use .text()
instead of .html()
in your case.
Hope this helps.