简体   繁体   中英

Checking looped radio buttons

I'm trying to make a quiz app using react, it has a list of questions and each question has an object of choices, and inside each question i have a previous and next buttons.

I managed to make everything work but the issue I'm facing is in the choices, they're radio buttons and each question has 4 radio buttons, when i choose the first answer of the first question it submits the value correctly but it checks all of the radio buttons in all of the questions, and if i went to the next question and selected a choice it submits it's value correctly but changes the checked for all of the questions and so on, the behavior i want is being able to check each radio button for each question separately without resetting the form or affecting other questions so when i click previous or next i be able see the choices i've selected, here is the code:

renderQuestions() {
    const questions = this.state.questions || [];
    if (questions) {
      return questions.map(question => (
        <React.Fragment>
        <p>{question.title}</p>
        <hr/>
        <p>Choose correct answer</p>
          {Object.keys(question.choices).map(function(key) {
            const value = question.choices[key];
            return (
                <input
                  type="radio"
                  label={value}
                  name="choice"
                  onChange={e => this.onChange(id, key, e)}
                  id={value}
                  checked={key}
                />
            );
          }, this)}
        </React.Fragment>
      ));
    }
  } 

The name attribute of the radio input must be unique per question:

 name={`choice-${questionId}`}

The browser enforces that only one radio can be checked for each name .

Its probably invalid HTML to have many checked=true for the same name. When you submit the form it will HTTP POST only one of the checked options.

Have a peruse of https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

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