0

I am trying to get the value of the radio button every time I change the active radio button in ReactJS, but the code is capturing the first change only.

in JSX

<input type="radio" name="radio" id="radio1" value="yes" onChange={(e) => this.radioChange(e)} />
<input type="radio" name="radio" id="radio2" value="no" onChange={(e) => this.radioChange(e)} />

and the function

radioChange = (e) => {
   console.log(e.target.value);
}

I need to show the selected radio button value in console every time I change the radio button selection

Please help.

5
  • 1
    Hi @Neel Debnath please see link jsbin.com/vodowiyoda/4/edit?js,output, it has sample of radio button functionality in react. Commented Sep 21, 2019 at 15:46
  • 1
    Even i post simple example of react js similar to you're question, Hope it helps you!!! Commented Sep 21, 2019 at 15:50
  • 1
    Can you show a minimal reproducible example? Is this a functional or class component? Commented Sep 21, 2019 at 15:52
  • @ankitkanojia this is surely helpful, Thanks for you time :) Commented Sep 21, 2019 at 16:03
  • @ggorlen this is a class component. Commented Sep 21, 2019 at 16:04

1 Answer 1

3

class App extends React.Component {
  
  radioChange(event) {
    console.log(event.target.value);
  }
  
  render() {
    return ( 
      <div>
        <input type="radio" name="radio" id="radio1" value="yes" onChange={(e) => this.radioChange(e)} /> Yes
        <input type="radio" name="radio" id="radio2" value="no" onChange={(e) => this.radioChange(e)} /> No
      </div>
     )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer, but still in my browser console, only the first response is showing.
Working now, I had checked on off the value in default. After removing this, it is working. Thanks a lot :)
So I guess the problem was that OP used an arrow function when they should have used a class function? A bit of description of why this solves the problem is always welcome for future visitors' benefit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.