Issue
I have an HTML input that accepts only numbers and on my script file I have I variable that gets the value of the input. What I want to do is create another variable that is equal to the first variable. When I put a number on the input field the value of the numInput
variable changes but not on the
value
variable.
EDIT
what I am trying to do is, I want to use the value of the value
variable on some functions that I will make.
const numInput = document.getElementById("input");
const value = numInput.value;
<header>
<input type="number" name="numInput" id="input" class="input" min="0" value="1" required>
</header>
Solution
JS objects are the only things in JS that are not cloned in assignment to a new variable. This includes arrays.
Therefore, to mimic the behaviour, you will need to update your value upon every change, typically by adding an event listener. I've chosen to use the change
event which will only fire upon blur if the value has changed of fields involving the keyboard and selection/alteration of range/date if the value has changed, though you could use the input
event if you want it to change on every keypress, too. Have a quick read:
- https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
- https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
When doing this, the value
can't be a constant, either, as it will change, so it must be a variable instead. I've opted for a let
declaration for better code isolation, but by all means use var
if you need more flexibility.
const numInput = document.getElementById("input");
let value = numInput.value;
numInput.addEventListener('change', () => {
value = numInput.value;
});
Answered By - SEoF
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.