简体   繁体   中英

get value from an input field in react

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> 

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 .

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> 

You should fetch value using event.target.value .

newName.addEventListener('input', function(event) {
  console.log('test ', event.target.value);

});

Working plunker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM