so I have an input element with the id of "answer" and a button. I've added an event listener for the button and tried to call a function that saves the text inside of the input into local storage. The console is telling me that "innerHTML" is null, but i'm not sure what I'm supposed to do.
<input type="text" id="answer" />
<button id="button">click me</button>
var inputAnswer = document.getElementById("#answer")
var buttonEl = document.getElementById("button")
buttonEl.addEventListener("click", saveToStorage())
function saveToStorage() {
localStorage.setItem("task", inputAnswer.innerHTML);
}
CodePudding user response:
<input type="text" id="answer" />
<button id="button">click me</button>
<script type="text/javascript">
var inputAnswer = document.getElementById("answer");
var buttonEl = document.getElementById("button");
buttonEl.addEventListener("click", addAnswerToLocalStorage);
function addAnswerToLocalStorage() {
const value = inputAnswer.value;
localStorage.setItem("answer", value);
}
</script>
There is mistake in getting the reference of input field. Instead of #answer document.getElementById("#answer")
it should be only answer only. Further, I checked it on my local machine and it is working fine.
CodePudding user response:
Change var inputAnswer = document.getElementById("#answer")
to var inputAnswer = document.getElementById("answer")
(remove the #
). getElementById()
expects an ID, no hashtag.
buttonEl.addEventListener("click", saveToStorage())
invokes the saveToStorage()
function immediately, which is not what you want. Instead, pass it as a reference: buttonEl.addEventListener("click", saveToStorage)
.