I am new to react. I have got a scenario where I have multiple radio button and few of the radio buttons have an input box associated with it. Like in the below image:
What I want is:
If the user checked any radio button which has an input box
associated with it, then that input box will become required field.
(display validation message "input is required" on button click.
otherwise display data on the console).
If everything is okay then On click of save button show data on the
console.
I have written some code. This code validates if none of the radio button is checked on button click (obvious case). But I am not understanding how to achieve the above requirement.
import React from "react";
const ContactUsForm = () => {
const isFormValid = () => {
var radios = document.getElementsByName("myRadio");
var isValid = false;
var i = 0;
while (!isValid && i < radios.length) {
if (radios[i].checked) isValid = true;
i++;
}
return isValid;
};
const handleButtonClick = () => {
if (!isFormValid()) {
alert("Select atleast one radio button");
} else {
alert("Success");
}
};
return (
<div>
{" "}
<br />
<label>
<input type="radio" name="myRadio" value="Graduate" /> I am graduate
</label>{" "}
<br />
<label>
<input type="radio" name="myRadio" value="Something" /> Some radio button
</label>{" "}
<br />
<label>
<input type="radio" name="myRadio" />I am graduate from university name
</label>{" "}
<input type="text" id="other" />
<br />
<label>
<input type="radio" name="myRadio" />
Other
</label>
<input type="text" id="other2" />
<br />
<button onClick={handleButtonClick} type="submit">
Save
</button>{" "}
<br />
</div>
);
};
export default ContactUsForm;
So you should use React State hook.
For every input, you need to add onClick event.
Declare state:
const [radioBtn, setRadioBtn] = useState(null);
Change state for each button click:
<input type="radio" name="myRadio" value="Graduate" onClick={() => setRadioBtn('Graduate')}/> I am graduate
In the end, all you need to do is to click Save and you can manage all the stuff you need in handleButtonClick
<button onClick={handleButtonClick} type="submit">
Save
</button>
Here you can validate all you need. Instead of alert you can use console.log(radioBtn) so you would get output to console.
const handleButtonClick = () => {
if (radioBtn) {
alert(radioBtn);
} else {
alert(radioBtn + ' fail');
}
}