Home > Software design >  Handle radio buttons selection with onChange event
Handle radio buttons selection with onChange event

Time:12-08

I have the following code:

let checkId = -1;

const checkChange= e => {
    checkId = e.target.id;
}

{ data.map(param=> (
    <div className="form-check form-check-inline">
        // paramd is an integer 1, 2, 3... etc. so is storing the desired value properly.
        <input className="form-check-input" type={'radio'} name={'radio'   param.Id} id={param.Id} value={data.Name} onChange={checkChange} checked={checkId == param.Id ? true : false} />
        <label className="form-check-label" for={param.Id}>{param.Name}</label>
    </div>
))}

What I want to do is to handle the checked attribute and keeping only one input selected so when I check other the previous loose the checked and set the clicked as checked.

CodePudding user response:

You must make sure that you use the same name for all the inputs. Additionally in the onChange handler, you must use e.target.value while setting the new value.

const [checkId, setCheckId] = useState(-1)


const checkChange = e => {
    setCheckId(e.target.value)
}

{ data.map((param, paramIdx)=> (
    <div key={paramIdx} className='form-check form-check-inline'>
        <input className='form-check-input' type='radio' name='for-something' id={param.Id} value={param.Name} onChange={checkChange} checked={checkId === param.Id} />
        <label className='form-check-label' for={param.Id}>{param.Name}</label>
    </div>
))}

Reference

  1. Radio Button

CodePudding user response:

I just found the solution of my problem. I was setting and reading my values properly. The problem was setting the checked=true/false attribute. I changed this:

<input className="form-check-input" type={'radio'} name={'radio'   param.Id} id={param.Id} value={data.Name} onChange={checkChange} checked={checkId == param.Id ? true : false} />

to

<input className="form-check-input" type={'radio'} name={'radio'   param.Id} id={param.Id} value={data.Name} onChange={checkChange} />

This handles the select/unselect cheked as I wanted. If anyone could share more details about why checked=condition returning true/false would be great.

  • Related