I am new at this and I'm trying to save multiple inputs to localStorage with one save button. Its saved second one but not the first one and I can't quite get it to work. Can you please tell me what is the reason? Why doesn't it save the first one?
My inputs and save button:
<body onl oad="init()">
<input type="text" id="myTxt1" placeholder="Type here ..." ></br></br></br>
<input type="text" id="myTxt2" placeholder="Type here ..."></br></br>
<button onclick="onSavePressed()">Save</button>
</body>
My script:
function init(){
if (localStorage.first1Box){
document.getElementById("myTxt1").value = localStorage.first1Box;
}
}
function onSavePressed(){
localStorage.first1Box = document.getElementById("myTxt1").value;
alert("Saved Successfully!!!");
}
function init(){
if (localStorage.second2Box){
document.getElementById("myTxt2").value = localStorage.second2Box;
}
}
function onSavePressed(){
localStorage.second2Box = document.getElementById("myTxt2").value;
alert("Saved Successfully!!!");
}
CodePudding user response:
Your function names conflict with each other try renaming them to something like init1
, init2
, onSavePressed1
, onSavePressed2
CodePudding user response:
If I am not wrong, you are creating functions with duplicate names (onSavePressed and init) which is against programming rules. You should have only one init and onSavePressed function. In this case, you just need a single onSavePressed function to solve the problem.
function onSavePressed(){
localStorage.setItem("first1Box", document.getElementById("myTxt1").value);
localStorage.setItem("second2Box", document.getElementById("myTxt2").value);
}