Home > OS >  How to select every event.target.value in a form
How to select every event.target.value in a form

Time:03-31

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:

<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?

CodePudding user response:

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
  • Related