Why is the value of my input always empty if I store it in a variable?
The testing
function handler is called every time the button is clicked.
In contrast, the inputValue
variable is evaluated only once when the code is firstly executed, at initial script evaluation during page load, and never again. The input value gets stored inside the variable and it never gets updated after that. (Strings are immutable in JavaScript: once you store a string in a variable, it won’t change unless you assign that variable to another value.)
If you want to refresh the value every time you click the button, you have to query the element every time:
const testing = () => {
const inputValue = document.getElementById("inputField").value;
alert(inputValue);
}
Or you can keep just a reference to the element and query the value
property every time:
const inputElement = document.getElementById("inputField");
const testing = () => alert(inputElement.value);
why input value is an empty string in this form?
You are retrieving the values of the inputs on page load (which is a blank string, because initially the input has no value).
Instead, get the value
inside the submit
event handler.
const formulario = document.querySelector("form");
const nombre = document.querySelector("#names");
const email = document.querySelector("#email");
const password = document.querySelector("#password");
let correctData = [];
let errors = [];
formulario.addEventListener("submit", (e) => {
e.preventDefault()
console.log(nombre.value)
console.log(email.value)
console.log(password.value)
});
<form action="signIn.html" method="get">
<input type="text" name="name" id="names" placeholder="Name">
<input type="email" name="email" id="email" placeholder="Email">
<input type="password" name="password" id="password" placeholder="Password">
<label for="terms">
<input type="checkbox" name="terms" id="terms" value="terms">I agree to the Terms and Privacy Policy
</label>
<div class="button">
<input class="btn signUp" type="submit" value="Sign Up">
</div>
Why is the variable holding the input value always logged as empty?
You were getting the value when the document is loaded. At this time, the value is empty. You need to get the value inside your click event.
(function() {
var button = document.getElementsByTagName("button");
var userInput = document.getElementById("user_input"); // Get only the element.
button[0].addEventListener("click", function() {
console.log(userInput.value); // Get the value here.
}, false);
})();
<form>
<input id="user_input" type="text" placeholder="add new task">
<button type="button">Add</button>
</form>
Variable with an input’s value is empty when assigned outside a function
Thats because you didn't put the value inside the function. Now var gg
will always hold the initial value. Which is on page load empty.
By putting it inside the function. The value will be retrieved as soon as the function gets triggered. In your case, you putted a onchange
trigger on it.
So when the value changes, the function will run at that moment, and retrieves the value inside the input field.
You can only get something if you ask for it. Or in this case JavaScript can only get something if something asks for it
Your function in the first case doens't ask for a value. In your seconds case, JavaScript
asks the value
of element #aa
Give empty input values a value only when they are empty/null, when a response function is executed in JavaScript
Please run following snippet. Once you type a name, it will be printed in the result div, once you erase EMPTY will be shown instead.
function getResponse(){
let val = document.getElementById("name").value
if (!val.length) val = "[empty]";
var resultValue = "Hello my name is " + val + ", nice to meet you.";
document.getElementById("result").innerHTML = resultValue;
}
<div class="formclass">
<label for="name">Input name here</label>
<input id="name" onInput="getResponse()"></input>
</div>
<div id="result"></div>
document.getElementById returns always null
You're retrieving the values on pageload, not on submit; they'll always be empty (not null, but the empty string). Change to:
document.getElementById('reg-form').addEventListener('submit', function(e) {
e.preventDefault();
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var reppassword = document.getElementById('passwordrep').value;
if (password == reppassword) {
console.log("Passwords match. Submitting...");
auth.createUserWithEmailAndPassword(email, password).then(userCredential => {
console.log('Signed up!');
});
}
});
Updating value of variable based on value of HTML input
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;
});
getElementById(x).value changes the output depending on the context
When you do
const number = document.getElementById("number").value; // will not give the expected value later on
You are getting the initial value of the input, which is empty, so you are getting a ""
string.
Then, when parsing it to an integer, you get NaN
since ""
cannot be a number
Instead, when doing
const numberCorrect = document.getElementById("number"); // will give the expected value later on
You are getting a reference to the input. So when you type something on it, the reference would be the same and calling parseInt(numberCorrect.value)
would give you the current value of the input.
Related Topics
Is There a Spec That the Id of Elements Should Be Made Global Variable
Check If an Element Contains a Class in JavaScript
How to Render an 'Atmosphere' Over a Rendering of the Earth in Three.Js
Submitting a Form on 'Enter' With Jquery
Refresh/Reload the Content in Div Using Jquery/Ajax
Get Next/Previous Element Using JavaScript
Removing All Script Tags from HTML With Js Regular Expression
How to Run an .Exe or .Bat File on 'Onclick' in Html
JavaScript Confirm Popup Yes, No Button Instead of Ok and Cancel
Which Browsers Support ≪Script Async="Async" /≫
Resizing an Image in an Html5 Canvas
What Browsers Support Html5 Websocket API
Way to Ng-Repeat Defined Number of Times Instead of Repeating Over Array
Difference Between Relative Path and Absolute Path in JavaScript
Is There an Onselect Event or Equivalent For HTML ≪Select≫