Reputation: 433
I try to make a form validator for a inputfield
. I try to get the input value from it using the getElementById().value
method. But when I console log the variable is empty. I tried to convert my variable into a string, it doesn't solve the problem.
When I type some extra text, the counter next to it increases. But no worthy value showed. How come it's not showing the right input value? thanks!
code of my validator:
const newName = document.getElementById('name');
let newNameValue = document.getElementById('name').value;
let beerArrayNames = this.state.beerArrayName;
newName.addEventListener('input', function(event) {
console.log('test ' + newNameValue);
if (beerArrayNames.includes(newNameValue)) {
newName.setCustomValidity('This already exist!');
} else {
newName.setCustomValidity('');
}
});
<p>Name: <input type='text' id='name' name='name' placeholder='fill in the name' required/> </p>
Upvotes: 1
Views: 7369
Reputation: 458
Even though this question has an accepted answer already, I think it's important to note that a solution more in line with React's design principles would be to not directly retrieve elements in the DOM and attach event listeners to them.
Instead, you can define an onChange
prop for the input element, which when triggered validates the input (and most likely update some UI state to show/hide error messages).
A good example of how to use of onChange
exists in the forms documentation.
Upvotes: 4
Reputation: 15292
You should fetch value using event.target.value
.
newName.addEventListener('input', function(event) {
console.log('test ', event.target.value);
});
Working plunker
Upvotes: 1
Reputation: 332
You need to set your variable inside your event listener (I commented out the other stuff because it doesn't work and is not part of your question)
newNameValue = this.value;
const newName = document.getElementById('name');
let newNameValue;
//let beerArrayNames = this.state.beerArrayName;
newName.addEventListener('input', function(event) {
newNameValue = this.value;
console.log('test ' + newNameValue);
//if (beerArrayNames.includes(newNameValue)) {
//newName.setCustomValidity('This already exist!');
//} else {
//newName.setCustomValidity('');
//}
});
<p>Name: <input type='text' id='name' name='name' placeholder='fill in the name' required/> </p>
Upvotes: 2