how to disable a button if more than once check box is checked in React JS
Wrap your input elements in a parent element like form
or div
.
Maintain state; an array that contains each box status (either true
or false
). When a box is changed call the handleChange
which will update the state.
The button disabled property should call a function called isDisabled
which will check to see if there are zero boxes checked or more than one box checked, returning true if the condition is matched.
const { useEffect, useState } = React;
function Example() {
const [boxes, setBoxes] = useState([]);
// In the text I suggested wrapping the inputs in
// a parent element. This was so we could use the following
// code to find its index within the list of inputs
// without adding any more code to the JSX
// Cribbed from https://stackoverflow.com/a/39395069/1377002
function handleChange(e) {
// Destructure the children from the parent of
// the element that was changed (ie all the input elements)
const { parentNode: { children } } = e.target;
// Find the index of the box that was changed
const index = [...children].indexOf(e.target);
// Copy the state
const newState = [...boxes];
// Toggle the boolean at the index of
// the `newState` array
newState[index] = !newState[index];
// Set the state with the updated array
setBoxes(newState);
}
// `filter` the boxes that return true.
// Return true if the length is 0 or > 1.
function isDisabled() {
const len = boxes.filter(box => box).length;
return len === 0 || len > 1;
}
return (
<div className="App">
<button disabled={isDisabled()}>Click Me</button>
<form>
<input type="checkbox" onChange={handleChange}/>
<input type="checkbox" onChange={handleChange}/>
<input type="checkbox" onChange={handleChange}/>
</form>
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Disable and Deselect Checkboxes by name in React
In your handleChange
function, you should change like below:
handleChange = (event, formKey) => {
const { name, checked } = event.target;
// Changed line
const updatedCheckedItems = name === 'All ages' ? { [name]: checked } : { ...this.state.checkedItems, [name]: checked };
this.setState(
{
checkedItems: updatedCheckedItems
},
() => console.log(this.state.checkedItems)
);
};
If the checkbox name is All ages
you should remove all the others, if not, just add one more property on the state object as usual.
checkbox defalut checked and also disabled in React.js not working
It is probably something wrong in your code somewhere else, please check this code - all looks fine.
class TodoApp extends React.Component { constructor(props) { super(props) } render() { return ( <div> <ul> <li> <label htmlFor="disabled-on" className="switch__label"> custom checkbox 1 <input type="checkbox" name="disabled-on" id="disabled-on" checked={true} disabled="disabled" className="switch__input switch__input--disabled-on" /> </label> </li><li> <label htmlFor="disabled-on" className="switch__label"> custom checkbox 2 <input type="checkbox" name="disabled-off" id="disabled-off" checked={true} className="switch__input switch__input--disabled-on" /> </label> </li> </ul> </div> ) }}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><div id="app"></div>
How to make button disabled if all checkbox are unchecked in react native
This is how you can do it
<PrimaryBtn label={'submit'} disabled={!this.state.notification.isContactByPost &&
!this.state.notification.isContactByEmail &&
!this.state.notification.isContactBySms} onPress={() =>
this.OnButtonClick(this.state.notification)} />
Hope this helps
Conditionally disable React Checkbox
The below code snippet will work fine for you. And you can sent object to the backend having maximum of only 3 properties set to true. Get the full code from codesandbox link https://codesandbox.io/s/emmeiwhite-0i8yh
import React from "react";
const checkboxes = [
{
name: "Math and economics",
key: "mathsandeconomics",
label: "Math and economics",
},
{
name: "Science",
key: "science",
label: "Science",
},
{
name: "history",
key: "history",
label: "history",
},
{
name: "literature",
key: "literature",
label: "literature",
},
];
class CheckboxComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
checkedItems: {},
count: 0,
};
}
handleChange = (event, formKey) => {
const { name, checked } = event.target;
const updatedCheckedItems = { ...this.state.checkedItems, [name]: checked };
this.setState({
checkedItems: updatedCheckedItems,
count: Object.values(updatedCheckedItems).filter((value) => value).length,
});
};
render = () => {
const checkedValues = { ...this.state.checkedItems };
const checkedCount = Object.values(checkedValues).filter((value) => value)
.length;
console.log(this.state.checkedItems);
return (
<div>
{checkboxes.map((item, index) => (
<label className={`form__field__input__label`} key={item.key}>
<input
type={`checkbox`}
name={item.name}
checked={this.state.checkedItems[item.name] || false}
onChange={this.handleChange}
disabled={!checkedValues[item.name] && checkedCount > 2}
/>
{item.name}
</label>
))}
</div>
);
};
}
export default CheckboxComponent;
Conditionally disabled React Checkboxes
You could keep an object in state that keep track of the checkbox values, and in your render method you can check if there are 2 or more checkboxes that are checked and use this to disable the others.
Example
class App extends React.Component { state = { checked: {} };
onSelectedChange = index => { this.setState(previousState => ({ checked: { ...previousState.checked, [index]: !previousState.checked[index] } })); };
render() { const { checked } = this.state; const checkedCount = Object.keys(checked).filter(key => checked[key]).length; const disabled = checkedCount > 1;
return ( <div> {Array.from({ length: 5 }, (_element, index) => ( <input key={index} onChange={() => this.onSelectedChange(index)} type="checkbox" checked={checked[index] || false} disabled={!checked[index] && disabled} /> ))} </div> ); }}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Related Topics
Javascript Add Class Active When Click a Link After Load Another Page
How to Combine Two Arrays into One Object With Key Value Pair
Fullcalendar - Change View for Mobile Devices
Show Form Fields Based on Selected Option
Deselect All Options in Multiple Select With 1 Option
How to Get the Value of Li on Dropdown Menu Click in Laravel Using Jquery
Reinitialize/Reset Dropzone After Form Is Submitted
Splitting an Array of Objects by Property
After Clicking a Button of Sweet Alert Call PHP File
Syntaxerror: Cannot Use Import Statement Outside a Module
Calculate the Bounding Box'S X, Y, Height and Width of a Rotated Element Via JavaScript
Converting Excel Date Serial Number to Date Using JavaScript
Javascript/Dom: How to Remove All Event Listeners of a Dom Object
Matching a Forward Slash With a Regex