I have created a multiple select object in my html and I want to set up the cookies so that whenever I reload the website, I get the selected values from the last session.
In order to set up the cookies, I have used the following javascript code:
window.onload = function(){
if(document.cookie.length != 0){
var nameValuearray = document.cookie.split("=");
list_values_selected=nameValuearray[1].split(",");
document.getElementById("ms_example2_sinB").value= list_values_selected;
}
}
function getvaluecookie(){
var d = new Date();
<!--Se define el tiempo en el que expirará la cookie-->
d.setTime(d.getTime() + (360*24*3600*1000));
var expires = "expires="+d.toUTCString();
<!--Se obtiene la lista de valores seleccionados-->
var selectedflavor = $("#ms_example2_sinB").val();
if (selectedflavor!="None selected"){
document.cookie= "flavor=" + selectedflavor + ";" + expires;
}
}
However, this doesn´t work as I want it to work. The cookie is correctly generated but I cannot manage to push the values from the list list_values_selected as selected values in the dropdown.
The html code is:
<form name="prueba_sin_B" method="POST" action="/" onsubmit="getvaluecookie()">
<select multiple id="ms_example2_sinB" name="select" >
<option value="Cheese" >Cheese</option>
<option value="tomatoes" >Tomatoes</option>
<option value="mozarella" >Mozzarella</option>
<option value="mushrooms" >Mushrooms</option>
<option value="pepperoni" >Pepperoni</option>
<option value="onions" >Onions</option>
</select>
</div>
<input type="submit" value="Submit" >
</div>
</form>
Thank you!
To make the options selected in multiselect, you have to set each option's selected
property to true
Use below code for window.onload
window.onload = function(){
if(document.cookie.length != 0){
var nameValuearray = document.cookie.split("=");
list_values_selected=nameValuearray[1].split(",");
$.each(list_values_selected, function(i,e){
$("#ms_example2_sinB option[value='" + e + "']").prop("selected", true);
});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.