Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select every event.target.value in a form

I have a form with three input tags. What I’m trying to accomplish is for the submit button on the form to be disabled until each input has at least one character in it.

Here is the code I am using:

const [isdisabled, setIsDisabled] = useState(true) 

const onChange = evt => {
    if (evt.target.value.trim().length < 1) {
      setIsDisabled(true) 
    } else {
      setIsDisabled(false)
    }
  }

my form:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<form id="form" onSubmit={onSubmit}>
      <h2>Create New Quiz</h2>
      <input id="newQuestion" placeholder="Enter question" />
      <input id="newTrueAnswer" placeholder="Enter true answer" />
      <input id="newFalseAnswer" placeholder="Enter false answer" />
      <button id="submitNewQuizBtn" disabled={isdisabled} >Submit new quiz</button>
    </form>

Then the buttons disable property is set to isDisabled. The problem with the code above is that setIsDisabled is set to true when either one of the three inputs has more than one character instead of when all three do. Is there a way for me to select the evt.target.value of all three inputs so that I can put that into my if statement?

>Solution :

How are you binding your form values as the user enters them? I would approach storing the data in your state and then your disabled check is just calculated based off of the state.

Simple example to get you on your way:

1: Create a state handler: 
const [newQuestion, setNewQuestion] = useState("")

Create your onChange handler to bind to state
2: <input id="newQuestion" placeholder="Enter question" onChange={(e) => setNewQuestion(e.target.value)} />

3: Do your disabled check based off of the values.
const isDisabled = newQuestion.length === 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading