how to get value of checkbox in react js
When using controlled components, you don't get the value, you simply give it to the HTML: your javascript state is the source of truth. That said, you should make the following changes:
use booleans for checkbox values:
this.state = {
rfp: false,
rfx: false,
rfp_x: false,
all: false
};
use event.target.checked
instead of event.target.value
:
this.setState({ [e.target.name]: e.target.checked });
Demo: https://codesandbox.io/s/polished-bush-5mf1n?file=/src/App.js
Get the value of checkbox using ref in React
For checkbox, use "checked" instead of "value":
var MyForm = React.createClass({
save: function () {
console.log(this.refs.check_me.checked);
},
render: function () {
return <div><h1>MyForm</h1>
<div className="checkbox">
<label>
<input type="checkbox" ref="check_me" /> Check me out
</label>
</div>
<button className="btn btn-default" onClick={this.save}>Submit</button>
</div>
}
});
As a result:
How to get checkbox value using React
As you pointed out, you can make the checkbox controlled with a React state, but it's not needed if you are inside a form, since the form owns the info of each input element inside of it, but in order to do that you must set a name
attribute on each input element, then you can read the values by instantiating a FormData:
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const data = formData.entries();
for (const entry of data) console.log(entry);
};
A working example here: https://stackblitz.com/edit/react-ictfjr
Get value from checked input in React
You could just bind the value and the update method to the state of your component and set the actions directly on the initial input markup with the onChange handler.
Note that React is unidirectional, not bidirectional, so it can good to try to control everything from React to your rendered html and not the other way or back and forth.
Following code is from: https://facebook.github.io/react/docs/forms.html
getInitialState: function() {
return {value: 'Hello!'};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
);
}
Getting values from checkbox, add them, and display the result (REACT)
You can achieve that by storing all selected items in a state and then using Array.prototype.reduce() to calculate the sum of all selected items.
const { useState } = React;
const App = () => {
const items = [
{
subscriberId: 1001,
amount: 100,
},
{
subscriberId: 1002,
amount: 300,
},
{
subscriberId: 1003,
amount: 500,
},
];
const [checked, setChecked] = useState([]);
const handleChange = (item, checked) =>
checked
? setChecked((prev) => [...prev, item])
: setChecked((prev) =>
prev.filter((c) => c.subscriberId !== item.subscriberId && c.amount != item.amount)
);
return (
<div>
{items.map((c) => {
return (
<div>
<input type="checkbox" onChange={(e) => handleChange(c, e.target.checked)} />
{`subscriber ${c.subscriberId}, amount ${c.amount}`}
</div>
);
})}
<p>Total {checked.reduce((sum, { amount }) => sum + amount, 0)}</p>
</div>
);
};
// Render it
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
How to get the value of ckeckbox element from a form submission in React.js?
FilterBox Component
function FilterBox(props) {
const categoriesFilters = props.categoriesCriteria.map((category, index) => {
return (
<label key={index}>
{category}
<input type="checkbox" value={category} name={category} />
</label>
);
});
const companiesFilters = props.companiesCriteria.map((company, index) => {
return (
<label key={index}>
{company}
<input type="checkbox" value={company} name={company} />
</label>
);
});
return (
<form
onSubmit={props.settingFilterCriteria}
className="product_creation_form"
>
<div>
<h5 className="filter_title">Categories</h5>
{categoriesFilters}
</div>
<div>
<h5 className="filter_title">Companies</h5>
{companiesFilters}
</div>
<button type="submit" className="form_button">
Apply
</button>
<button type="reset" className="form_button">
Clear All
</button>
</form>
);
}
App Component:
function App() {
const [companies] = React.useState(["companyOne", "companyTwo"]);
const [categories] = React.useState(["categoryOne", "categoryTwo"]);
const onFilteringHandler = (e) => {
e.preventDefault();
const filterCriteria = { companies: [], categories: [] };
for (const element of e.target) {
if (element.type === "checkbox" && element.checked) {
if (companies.includes(element.value)) {
filterCriteria.companies.push(element.name);
}
if (categories.includes(element.value)) {
filterCriteria.categories.push(element.name);
}
}
}
console.log(filterCriteria);
};
return (
<FilterBox
categoriesCriteria={categories}
settingFilterCriteria={onFilteringHandler}
companiesCriteria={companies}
/>
);
}
I took the liberty to disconnect the initial API loading of the companies
& categories
react state arrays and hardcoded them for simplicity. The below code should be enough to send meaningful data to be able to filter out on the backend.
I took the approach with a non-controlled form state, as your code seemed to favour this kind of approach. You can try and keep the filter values in the react state too but I believe this complicates the solution a bit (especially that state update is async) and it seems that you only need to collect the current filters state value on a button press. If however, you need it for some other purposes, then a controlled form state would most likely be needed.
get value of checkbox in react js
you can acess whether checkbox is checkd using e.target.checked
:
onChangeEtat(e) {
this.setState({
etat: e.target.checked
});
}
Related Topics
How to Change Background Color of a Row on Checkbox Selection
Javascript Json Parsing Error: Unexpected Token ' in Json At Position 1
How to Fix Problem Closing Dropdown When I Click Outside It
Prevent Particular Child Element from Firing Parent'S Mouseover Event in Jquery
How to Combine Two Arrays into One Object With Key Value Pair
Javascript Function (Input Date Bigger Than Today Date)
React Import: Navigate One Folder Up
Can We Call the Function Written in One JavaScript in Another Js File
Connection Refused! Is Selenium Server Started
How to Separate an Integer into Separate Digits in an Array in JavaScript
How to Detect If a Browser Is Blocking a Popup
Javascript Odd and Even Separation in an Array of Numbers
How to Align Text Input Correctly in React Native
How to Pass Value into Href Link of a Bootstrap Modal