Reputation: 49
I'm trying to save values from user input on the session storage and then retrieve them. All of the values retrieve except the value for the radio choise. it is the gender input.
It works with firstname, lastname and dateofbirth, but the gender stays empty. I can see that all the values are saved on the session storage, including gender. If I choose "male", "male" will be stored as true and the rest as false.
function validate(){
//get form values
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var dateofbirth = document.getElementById("dateofbirth").value;
var female = document.getElementById("female").checked;
var male = document.getElementById("male").checked;
var other = document.getElementById("other").checked;
else {
setDetails(firstname, lastname, dateofbirth, female, male, other);
}
}
function getDetails(){
if (typeof(Storage)!=="undefined"){
if (sessionStorage.getItem("firstname") !== null){
document.getElementById("firstname").value = sessionStorage.getItem("firstname");
}
if (sessionStorage.getItem("lastname") !== null){
document.getElementById("lastname").value = sessionStorage.getItem("lastname");
}
if (sessionStorage.getItem("dateofbirth") !== null){
document.getElementById("dateofbirth").value = sessionStorage.getItem("dateofbirth");
}
if (sessionStorage.getItem("female") == true){
document.getElementById("female").checked = sessionStorage.getItem("female");
}
if (sessionStorage.getItem("male") == true){
document.getElementById("male").checked = sessionStorage.getItem("male");
}
if (sessionStorage.getItem("other") == true){
document.getElementById("other").checked = sessionStorage.getItem("other");
}
}
function setDetails(firstname, lastname, dateofbirth, female, male, other) {
if (typeof(Storage)!=="undefined"){
sessionStorage.setItem("firstname", firstname);
sessionStorage.setItem("lastname", lastname);
sessionStorage.setItem("dateofbirth", dateofbirth);
sessionStorage.setItem("female", female);
sessionStorage.setItem("male", male);
sessionStorage.setItem("other", other);
}
}
Upvotes: 0
Views: 157
Reputation: 867
Values saved in sessionStorage and localStorage are always strings. When you save a boolean value of true/false, you are in fact saving a string of "true" or "false".
Therefore, when you set the "checked" value of the input, you need to convert the new value to a boolean. For instance:
if (sessionStorage.getItem("female") === 'true') {
document.getElementById("female").checked = sessionStorage.getItem("female") === 'true';
}
Or better yet:
var female = sessionStorage.getItem("female") === 'true';
if (female) {
document.getElementById("female").checked = female;
}
Upvotes: 1