Radio buttons with action and store - javascript

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;

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');
}
}

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

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>
);
}

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

Is there a way to pass the value from a button to a form when the user clicks submit?

I am trying to get the value from 5 buttons, whichever the user selects, and then once they fill the form out, I want the button value that they selected to be shown on the "summary" screen.
Is there a way to get the value of the button, along with all the other form details, and then send all those details to a new screen that shows all the information the user has entered? Something like a confirmation screen to confirm all details before they send their enquiry.
What I've been trying:
Buttons:
<div class="card">
<h1 id="size">Select your size*</h1>
<ul class="size-list">
<li>
<button class="size-link" id="size-button" value="Small">
Small
</button>
</li>
<li>
<button class="size-link" id="size-button2" value="Medium">
Medium
</button>
</li>
<li>
<button class="size-link" id="size-button3" value="Large">
Large
</button>
</li>
<li>
<button class="size-link" id="size-button4" value="X Large">
X Large
</button>
</li>
<li>
<button class="size-link" id="size-button5" value="XX Large">
XX Large
</button>
</li>
</ul>
</div>
I want to get the value from each button above as well as all the information from the form below and send it to the "Summary" screen.
Form:
<form method="GET" action="final.html" id="myform" class="contact-form">
<label id="fullname">Full Name*</label> <br />
<input name="name" id="name" class="txt-form name" type="text" />
<label id="mail">Email*</label> <br />
<input name="email" id="email" class="txt-form email" type="email" />
<label id="cheap">Have you found this item cheaper on a competitor website?*</label>
<br />
<label>
<input id="radio1" type="radio" name="radio" value="Yes"> <label for="radio1">
<span><span></span></span>Yes</label>
<input id="radio2" type="radio" name="radio" value="No"> <label for="radio2">
<span><span></span></span>No</label> <br />
</label>
<div id="url">
<label>Competitor URL</label>
<input name="url_name" id="url-link" class="txt-form" type="url">
</div>
<label id="msg">Enquiry Message*
<span id="characters">(0/200)</span></label>
<textarea name="message" id="message" class="txt-form message" type="textarea"></textarea>
<p id="asterisk">
Fields marked with an *asterisk are compulsory
</p>
<input type="submit" class=" btn" id="submit" value="Submit your enquiry">
</form>
Summary Screen:
<div id="app" class="contact-main">
<form id="myform" class="contact-form"></form>
</div>
Javascript:
const urlName = new URL(location.href);
document.getElementById('app').innerHTML = `
<label>Full Name: </label> ${urlName.searchParams.get("name") || "N/A"}
<br /><br />
<label>Email:</label> ${urlName.searchParams.get("email") || "N/A"}<br /><br />
<label>Size of item selected:</label> ${urlName.searchParams.get("sizes") || "N/A"} <br /><br />
<label>Have you found this item cheaper on a competitor
website?
</label> ${urlName.searchParams.get("radio") || "N/A" } <br /><br />
<div>
<label>Competitor URL:</label> ${urlName.searchParams.get("url-link") || "N/A"} <br /><br />
</div>
<label id="msg">Enquiry Message:</label> <br/> "${urlName.searchParams.get("message") || "N/A"}" <br /><br />
`;
I am able to get everything from the form but the "Size of item selected". I know this is because I am trying to retrieve it from the url.searchPram, however the buttons are not included on the form so I am just wondering if there's any other way?
Regarding: "Is there a way to get the value of the button"
I assume you mean the value of the clicked button. Yes, there is a way, by setting up a click listener.
Rather than setting up a click listener for each button, you can set up just one on the parent that contains the buttons. To make things easy, set an id for the enclosing <ul>:
<ul class="size-list" id="size-list">
Then set a listener on that <ul>:
document.getElementById('size-list').addEventListener('click', evt => {
let clickedButton = evt.target;
let btnValue = clickedButton.value;
}
You now have the value of the clicked button.
Storing Button's Value into a Form Element
If you need to store that value into a form element, so that value is included when the form is submitted, this can also be done with a hidden input. Let's create one with an id and name of "size":
<form method="GET" action="final.html" id="myform" class="contact-form">
<input type="hidden" id="size" name="size" value="" />
</form>
Then, just a slight modification of the click handler will store the button's value into the hidden input:
document.getElementById('size-list').addEventListener('click', evt => {
let clickedButton = evt.target;
let btnValue = clickedButton.value;
document.getElementById('size').value = btnValue;
}
That's all, the "size" value will now be sent when the form is submitted.
SOLUTION:
Add a hidden input on your form for the data. Based on your HTML and JavaScript it would be:
<input type="hidden" id="sizes" name="sizes" value="Medium">
Notice that I added a value attribute of Medium just in case the user hits submit on the form without actually pressing on of the size buttons. You could remove this and add code in your JavaScript to check if sizes is empty/ missing.
Next you need to add a click event listener to each button that will call a function when they are clicked. The JavaScript way:
// Way 1 using older JS.
var buttons = document.querySelectorAll('.size-link');
for( var x = 0; x < buttons.length; x++ ){
buttons[x].addEventListener( 'click', recordButtonSize );
}
// Way 2 using newer JS without an arrow function.
var buttons = document.querySelectorAll('.size-link');
buttons.forEach( function( button ) {
button.addEventListener( 'click', recordButtonSize );
} );
Or directly in the HTML add an onclick to each button:
<button class="size-link" value="..." onclick="recordButtonSize">...</button>
Notice that I removed your ID's. You don't really need them regardless of which solution you choose to use, the JavaScript or HTML.
And now we make the recordButtonSize function that will copy the data from the pressed button over to the hidden input:
function recordButtonSize(){
// Get the element that was clicked on.
var elem = event.target || event.srcElemnt;
// Depending on browsers / where the user clicked we may not be on the button.
if( elem.nodeName != 'BUTTON' ){
elem = elem.closest('button');
}
// Now pull the value from the button and place in the hidden input.
document.getElementById('sizes').value = elem.value;
}
NOTES:
I don't know if button elements care allowed to have value attributes so you may need to switch that to a dataset.
This solution gets the size placed into an input on the form but DOES NOT submit the form. That isn't hard to add but I will leave it as an exercise for you to figure out.
This answer uses a mix of older and newer JavaScript which will work fine on any modern browser but IE 11. See here: closest

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')
);

Categories

Resources