What I want to do is to be able to change the value of val once btn-here has been clicked. I have the following code but it is not working. what am I missing?
var btn = document.getElementById('btn-here');
var val = document.getElementById('text-here').value;
btn.addEventListener("click", () => {
var val = '100';
});
CodePudding user response:
If you just want to change the value of your variable, you don't need to declare that again. So your code will look something like:
var btn = document.getElementById('btn-here');
var val = document.getElementById('text-here').value;
btn.addEventListener("click", () => {
val = '100';
});
CodePudding user response:
The below code snippet should be helpful in clarifying why the code in the question does not achieve it's expected objective as well as provide an alternative that works.
Code Snippet
var btn = document.getElementById('btn-here');
// in below, one is directly accessing the "value"
var val = document.getElementById('text-here').value;
btn.addEventListener("click", () => {
// var val = '100'; // even if one removes "var", the value will still
val = '100'; // not be assigned to element "text-here"
console.log('val is now ', val);
console.log('but, "text-here" element value remains: ', document.getElementById('text-here').value);
});
// below is one way to achieve the expected objective
// it uses no variables & directly manipulates the HTML elements
document.getElementById("btn-here-works").addEventListener('click', () => {
document.getElementById("text-here").value = '100';
});
// below is another alternative which uses variables
// which resembles closely what the OP has described in their question
// declare btn to hold the element with id "btn-here"
const btn2 = document.getElementById('btn-here2');
// declare userInput to hold "text-here" (which is <input />)
const userInput = document.getElementById('text-here2');
// add click event listner where userInput.value is assigned a value 100
btn2.addEventListener("click", () => {
userInput.value = '100';
});
<button id="btn-here">button</button>
<input id="text-here" />
<button id="btn-here-works">button works</button>
<br/><br/>
<button id="btn-here2">button-2</button>
<input id="text-here2" />
Explanation
- It is my understanding that
var val = document.getElementById('text-here').value;
provides a read-only access to thevalue
prop of the HTML-element - Hence when assigning
100
toval
, the HTML-element remains unaffected - Modifying
var val = '100';
toval = 100
does not achieve what OP expects - Instead, if one accesses the HTML-element (& not it's
value
prop) by using a variable such asuserInput
- Then, one is able to assign a value to
userInput.value
which then changes thevalue
prop of the HTML element.