I'm using sessionStorage to update a button text. I've got the button IDs stored in an array. My question is how do I update the button text using the sessionStorage values? Below is an example.
var btnArr = [fruit, veggies, dessert];
if (sessionStorage.getItem("val0")) {
button0 = sessionStorage.getItem("val0");
button1 = sessionStorage.getItem("val1");
button2 = sessionStorage.getItem("val2");
for(i = 0; i<btnArr.length; i++){
$('#'+btnArr[i]).text("button"+i); // How do I update this value here?
}
}
Use array
to store button values same as you've btnArr
array for the values. Get the values from sessionStorage
and can be used in for
loop using index
.
var btnArr = [fruit, veggies, dessert];
var buttonValues = []; // For buttons
if (sessionStorage.getItem("val0")) {
// Add values in array
buttonValues.push(sessionStorage.getItem("val0"));
buttonValues.push(sessionStorage.getItem("val1"));
buttonValues.push(sessionStorage.getItem("val2"));
for (i = 0; i < btnArr.length; i++) {
$('#' + btnArr[i]).text(buttonValues[i]); // Use values from array
}
}
OR
Using sessionStorage
values in array
directly.
var btnArr = [fruit, veggies, dessert];
if (sessionStorage.getItem("val0")) {
var buttonValues = [sessionStorage.getItem("val0"), sessionStorage.getItem("val1"), sessionStorage.getItem("val2")]; // Add values in array
for (i = 0; i < btnArr.length; i++) {
$('#' + btnArr[i]).text(buttonValues[i]); // Get values from array
}
}