Can't select radio buttons when checked status has some logic - javascript

I have a couple of checkboxes that are refusing to be checked.
export default function App() {
let model = {};
return (
<div className="App">
<h1>Hello React Radio Buttons</h1>
<p>
Sure the model object is empty, so initially the radio will be
unchecked, but why can't I manually check it?
</p>
<div>
<input type="radio" id="opt1" checked={model.selection === "opt1"} />
<label htmlFor="opt1">Option 1</label>
</div>
<div>
<input type="radio" id="opt2" checked={model.selection === "opt2"} />
<label htmlFor="opt2">Option 2</label>
</div>
</div>
);
}
Here is a sandbox link.
The above is a simple test scenario, but I am glad I was able to replicate the problem.
The real scenario is I am trying to maintain the status of what radio button was checked when I come back to the page from an error state (i.e. form was submitted, there were errors, I want to come back to the page and maintain the selections).

Because your model does't have selection key. It's better to use useStates hook same as bellow:
export default function App() {
let model = {};
const [checked1, setChecked1] = useState(model.selection === "opt1");
const [checked2, setChecked2] = useState(model.selection === "opt2");
return (
<div className="App">
<h1>Hello React Radio Buttons</h1>
<p>
Sure the model object is empty, so initially the radio will be
unchecked, but why can't I manually check it?
</p>
<div>
<input
type="radio"
id="opt1"
onChange={() => setChecked1(!checked1)}
checked={checked1}
/>
<label htmlFor="opt1">Option 1</label>
</div>
<div>
<input
type="radio"
id="opt2"
onChange={() => setChecked2(!checked2)}
checked={checked2}
/>
<label htmlFor="opt2">Option 2</label>
</div>
</div>
);
}

Related

How to validate and get data of a radio button with input box in reactjs?

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;
Can anybody help me in achieving the above requirement in react? Thank You
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');
}
}

How do i get the value of the checked radio button on react,js

I am making an organized todo list and i would love to have it that if i select any of the radio buttons i can put the input in either of the three options array (array not added in code, in a parent component).
I need a function which can tell me which radio button is checked and how to get the id or value of the checked.
const AddTodo = ({ submit, textColor }) => {
return (
<div className="displayFlex justCenter">
<form onSubmit={submit}>
<div>
<input
type="text"
name="newTask"
id="inp"
placeholder="Enter New Task..."
/>
<input
style={{ color: textColor }}
className="btn"
type="submit"
value="Add Task"
/>
</div>
<div>
<span>
<input type="radio" id="todo" name="radioButton" value="toDo" />
<label>To do</label>
</span>
<span>
<input
type="radio"
id="progress"
name="radioButton"
value="inProgress"
/>
<label>In Progress</label>
</span>
<span>
<input type="radio" id="done" name="radioButton" value="done" />
<label>Done</label>
</span>
</div>
</form>
</div>
);
};
export default AddTodo;
Inside your submit function, or another function which you call inside submit, you can get the value of checked radio button.
function submit(event) {
[].forEach.call(event.target.elements, function(ele) {
if (ele.checked) {
console.log(ele.value); // get the checked radio button's value
}
});
event.preventDefault();
}
Here is a working stackblitz url

React controlled radio buttons not being checked

I have a child component that receives props from a parent. In the child component it renders a couple radio buttons like this:
<div>
<div className="radio">
<label>
<input
type="radio"
name="value"
onChange={this._handleInputChange}
value="1"
checked={this.props.value === "1"}
/>
True
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
name="value"
onChange={this._handleInputChange}
value="0"
checked={this.props.value === "0"}
/>
False
</label>
</div>
</div>
handleInputChange just calls a parent method like so:
_handleInputChange(e) {
this.props.handleChange(e);
}
that will set the state of the parent component to the value selected in the radio buttons (i.e. "1" or "0"). The issue im having is that the checked conditionals return the correct props, but they function strangely. It almost seems like when the radio input receives a new prop value, it doesn't re render with checked. When the component first renders, the props.value is an empty string. When a user selects a radio button it changes the state of the parent component with _handleInputChange and then sends that value back down for the conditionals.
Thanks to some of the help here and on IRC I figured out it was a preventDefault in my event handler. After removing that it worked perfectly!
You must use state for checked property if you want react re-render radio button.
Example:
<div>
<div className="radio">
<label>
<input
type="radio"
name="value"
onChange={this._handleInputChange}
value="1"
checked={this.state.radioButton1}
/>
True
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
name="value"
onChange={this._handleInputChange}
value="0"
checked={this.state.radioButton2}
/>
False
</label>
</div>
</div>
You also set value for state like this (alternatively, you can initialize it with getInitialState):
this.setState({
radioButton1 : props.value ==="1",
radioButton2 :props.value ==="0"
});
And in _handleInputChange function you're able to know that radio button is checked or unchecked by checking it's state.
_handleInputChange(e) {
var isChecked = e.target.value ==="1" ? this.state.radioButton1 : this.state.radioButton2;
this.props.handleChange(e);
}
use bind method to bind context this._handleInputChange.bind(this) in the constructor,or use (e)=>this._handleInputChange(e) on click ,when the event handler executed normally has no context.
or declared as this below,it can bind this automatically:
class ButtonGroup extends Component{
....
_handleInputChange= (e)=>{
...
}
sample below:
class ButtonGroup extends Component {
render() {
return (
<div>
<div className="radio">
<label>
<input
type="radio"
name="value"
onChange={(e) => this._handleInputChange(e)}
value="1"
checked={this.props.value === "1"}
/>
True
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
name="value"
onChange={(e) => this._handleInputChange(e)}
value="0"
checked={this.props.value === "0"}
/>
False
</label>
</div>
</div>
);
}
_handleInputChange(e) {
this.props.handleChange(e);
}
}
class Form extends Component {
constructor(props) {
super(props);
this.state = {value: '1'};
}
render() {
var value = this.state.value;
return <ButtonGroup value={value} handleChange={(e) => this.valueChanged(e)}/>
}
valueChanged(e) {
this.setState({value: e.target.value});
}
}
ReactDOM.render(
<Form />,
document.getElementById('container')
);

Radio buttons with action and store

I am working with 4 radio buttons where I need to take the 2 options selected by the user and send it to a socket, but first, I need to know how to update the options selected using an action and a store
here the code where you can see the buttons
class BetBehindModal extends Component {
constructor (props) {
super(props);
}
render () {
return (
<div>
<div>
<p>Bet Behind Settings</p>
<p>When seated player Doubles:</p>
<form>
<input type="radio" value="double" name="doubles" /> Always Double my bet <br />
<input type="radio" value="nodouble" name="doubles" /> Never Double my bet
<p>When seated player Splits:</p>
<input type="radio" value="split" name="splits" /> Always Split <br />
<input type="radio" value="nosplit" name="splits" /> Assign bet to 1st hand
</form>
<hr />
<button className="toggleModalBtn" type="submit" onClick={this._confirm}>Confirm</button>
</div>
</div>
);
}
}
export default BetBehindModal;
so, there are 4 options, the user has the right to choose 2 of those 4. I need to send that info to a socket and also to a backend made in Nodejs, but the most important part is, how to work with this with the action and the store?
As far as I understand the question, you having a hard time trying to update the state of your component based on the radio buttons. As a way to do it, you may add onChange handler:
class BetBehindModal extends Component {
constructor (props) {
super(props);
this.onDoublesChange = this.onDoublesChange.bind(this);
this.onSplitsChange = this.onSplitsChange.bind(this);
}
render () {
return (
<div>
<div>
<p>Bet Behind Settings</p>
<p>When seated player Doubles:</p>
<form>
<input type="radio" value="double" name="doubles" onChange={this.onDoublesChange}/> Always Double my bet <br />
<input type="radio" value="nodouble" name="doubles" onChange={this.onDoublesChange}/> Never Double my bet
<p>When seated player Splits:</p>
<input type="radio" value="split" name="splits" onChange={this.onSplitsChange}/> Always Split <br />
<input type="radio" value="nosplit" name="splits" onChange={this.onSplitsChange}/> Assign bet to 1st hand
</form>
<hr />
<button className="toggleModalBtn" type="submit" onClick={this._confirm}>Confirm</button>
</div>
</div>
);
}
onDoublesChange({ target }) {
if (target.checked) this.setState({ doubles: target.value });
}
onSplitsChange({ target }) {
if (target.checked) this.setState({ splits: target.value });
}
}
export default BetBehindModal;

Submitting radio inputs with ReactJs and setting active class to the current selection

I am trying to submit the event_type attached to the option chosen from the radio buttons. For example if "professional" is the chosen option, I would like to set the event_type to that on the submitted data. Also setting the "active" class to the label that is currently selected. I am trying to figure out how to do that. Any help? Thanks
<label htmlFor="professional" className="EventTypeFieldButton EventTypeFieldProfessional active">
<span className="TypeDot"></span>Professional
</label>
<input type="radio" name="event_type" id="professional" value="professional" />
<label htmlFor="academic" className="EventTypeFieldButton EventTypeFieldAcademic">
<span className="TypeDot"></span>Academic
</label>
<input type="radio" name="event_type" id="academic" value="academic" />
<label htmlFor="miscellaneous" className="EventTypeFieldButton EventTypeFieldMiscellaneous">
<span className="TypeDot"></span>Miscellaneous
</label>
<input type="radio" name="event_type" id="miscellaneous" value="miscellaneous" />
var MyComponent = React.createClass({
render: function() {
<label className={this.state.isActive}>
<input type="radio" name="event_type" id="professional" value="professional" onChange={this._onselectRadio(e)} />
</label>
},
_onselectRadio: function(e) {
var event_type= e.target.name;
// submit stuff
this.setState({
isActive = "active"
});
}
});
Since you have several label you'll have to render your radio inputs dynamically and check if e.target.name is equal to your label id/name , something like that.

Categories

Resources