How to organize multiple checkboxes? - javascript

I want to organize multiple checkboxes. I decided to keep an array of ids of chosen boxes in state.And using method want to give them statuses "checked".
constructor(props) {
super(props);
this.state = {
checkboxes: []
}
}
for(let i=0; i<checkboxData.length; i++) {
checkboxes.push(
<List.Item key = { checkboxData[i].id }>
<div className="ui checkbox">
<input type="radio"
id={checkboxData[i].id}
checked={ ()=>this.getCheckboxStatus(checkboxData[i].id)}
onChange = { this.setTag }
/>
<label>{checkboxData[i].name}</label>
</div>
<List.Content floated="right" >
<Label>
0
</Label>
</List.Content>
</List.Item>
);
}
getCheckboxStatus = checkBoxId => {
let { checkboxes } =this.props;
console.log('IDS', checkBoxId)
if (checkboxes.length === 0) {
return false;
} else if (checkboxes.indexOf(checkBoxId)!==-1){
return true;
}
return false;
};
setTag = e => {
let { checkboxes } = this.state;
if ( checkboxes.length === 0 ) {
checkboxes.push( e.target.id );
} else {
if(checkboxes.indexOf(e.target.id)!==-1) {
checkboxes.splice(checkboxes.indexOf(e.target.id),1);
} else {
checkboxes.push( e.target.id );
}
}
this.setState({ checkboxes: checkboxes })
}
React renders it and throws in console:
Warning: Invalid value for prop `checked` on <input> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM.
How I understand this is because I'm using method for checked attribute. How can I do same thing and not receive warning?

Your input type needs to be checkbox, not radio. You also need to reference state with your checked attribute.
<input
type="checkbox"
id={checkboxData[i].id}
checked={this.state.checkBoxes[i]}
onChange={this.setTag}
/>
This will set state with true or false depending on the state of the checkbox

Related

checking whether or not any checkbox input is checked from array of input

I have a node list of chechbox inputs
const searchSizeSelectionInputs = document.querySelectorAll(
".sizeHolderFilter > input")
I have written a function to check whether or not any checkbox is checked or not, the function is
const activationChecker = ()=>{
if (
availabilityInStoreOptions[0].classList.contains("activeSortOptionSP") ||
availabilityInStoreOptions[1].classList.contains("activeSortOptionSP")
) {
isAvailabilityInStorActive = true;
}
if( !availabilityInStoreOptions[0].classList.contains("activeSortOptionSP") &&
!availabilityInStoreOptions[1].classList.contains("activeSortOptionSP")) {
isAvailabilityInStorActive = false;
}
searchSizeSelectionInputs.forEach(input => {
if (input.checked) {
isSizeInputChecked = true;
} else {
let isSizeInputChecked = false;
}
});
searchColorSelectionInputs.forEach(input => {
if (input.checked) {
isColorInputChecked = true;
} else {
let isColorInputChecked = false;
}
});
};
the thing is, when I check the result of isSizeInputChecked or isColorInputChecked it gives me faulty answers, for example when I check the checkbox it gives me true and when I uncheck the checkbox it still gives me true, I tested the same code on one single object and it works beautifully,I believe I do have a problem on doing this on a node list. This must be the wrong way:
searchSizeSelectionInputs.forEach(input => {
if (input.checked) {
isSizeInputChecked = true;
} else {
let isSizeInputChecked = false;
}
How can I check if any checkbox is checked or not any of them is checked?
function getCheckedData() {
let atleastOneChecked=Array.from(document.querySelectorAll('.checkbox'))
.some(
function(inputCheckbox) {
return inputCheckbox.checked;
}
);
let allChecked=Array.from(document.querySelectorAll('.checkbox'))
.every(
function(inputCheckbox) {
return inputCheckbox.checked;
}
);
console.log('atleastOneChecked',atleastOneChecked);
console.log('allChekecked',allChecked);
}
<input type="checkbox" class='checkbox'>
<input type="checkbox" class='checkbox'>
<button onclick="getCheckedData()">Get checked data</button>
The document.querySelectorAll returns a NodeList and it is not an array. We have to convert node list into an array using Array.from and use the some function from Array to get atleast one of the element is checked or not.

If I use defaultChecked, sorting table columns does not change the position of the checkbox

If I use "defaultChecked", sorting table columns does not change the position of the checkbox.
If use "checked", I can change position but checkbox doesn't work correctly.
How can I fix it?
Here is the code: https://jsfiddle.net/sakanyan/e2a56mbk/29/
enter code here
<input type="checkbox" checked={item.hasItem} /*OR
defaultChecked={item.hasItem} */ />
Missing something like this:
constructor(props) {
//....
this.onCheck = this.onCheck.bind(this);
}
//...
onCheck(event) {
let s = Object.assign({}, this.state);
let d = s.data.find( s => s.id == e.target.name );
if( !d ) return;
d.hasItem = !d.hasItem;
this.setState(s);
}
render() {
//...
<input name = {item.id} type='checkbox' checked={item.hasItems} onChange={this.onCheck} />
//...
}
Previously, you're checkbox were never updated (in state) so the sort appears to be wrong.
Try this,
constructor(props) {
super(props)
state = {
hasItems = false;
}
}
handleCheck = event => {
this.setState({hasItems : !this.state.hasItems })
}
render(){
return(
//....
<input
type="checkbox"
checked={this.state.hasItem}
onChange={this.handleCheck}
>
//....
)
}

Change color of all occurrences of a character javascript/reactjs

I am working with reactjs have a form with multiple input fields and some of them have labels with an asterisk to indicate that the field is mandatory. I want to change the color of all the asterisks(*) to red for better visibility to the user. How can I change the color of all occurrences of the asterisk in my form to red at once?
PS : I don't want to put the asterisk in a span or a div. Rather I would like to write code so that every asterisk in the form gets the color red with a single piece of global code.
You should wrap asterisks in span element and assign some class. So you can give color to that class element in your css file.
Like this
<span class="required">*</span>
And in CSS
.required
{
color:red;
}
It's rather unclear what exactly you're trying to accomplish without having any code to reference. But I'm assuming what you're actually trying to highlight the asterisks (*) belonging to labels for fields that are empty during form-submission.
Try something like this: https://codesandbox.io/s/holy-leftpad-hw1oe
class App extends React.Component {
state = {
name: "",
password: "",
errors: false
};
handleOnChange = event => {
this.setState({
[event.target.name]: event.target.value
});
};
handleOnSubmit = event => {
event.preventDefault();
const { name, password } = this.state;
if (name.length === 0 || password.length === 0) {
this.setState({
errors: true
});
} else {
this.setState({
errors: false
});
}
};
render() {
const { name, password, errors } = this.state;
return (
<form onSubmit={this.handleOnSubmit}>
<label>
Name{" "}
<span
className={errors && name.length === 0 ? "error-label" : "label"}
>
(*)
</span>
</label>
<input name="name" onChange={this.handleOnChange} />
<label>
Password
<span
className={
errors && password.length === 0 ? "error-label" : "label"
}
>
(*)
</span>
</label>
<input name="password" onChange={this.handleOnChange} />
<button type="submit">Submit</button>
</form>
);
}
}

uncheck checkbox programmatically in reactjs

I am messing with checkboxes and I want to know that is there a way in which I can uncheck a checkbox on click of a button by calling a function?? If so? How can I do that?
<input type="checkbox" className="checkbox"/>
<button onClick={()=>this.unCheck()}
How can I uncheck the checkbox programmatically and what if I have multiple checkboxes generated dynamically using map function.
How can I uncheck them If I want to?
There is property of checkbox checked you can use that to toggle the status of check box.
Possible Ways:
1- You can use ref with check boxes, and onClick of button, by using ref you can unCheck the box.
2- You can use controlled element, means store the status of check box inside a state variable and update that when button clicked.
Check this example by using ref, assign a unique ref to each check box then pass the index of that item inside onClick function, use that index to toggle specific checkBox:
class App extends React.Component{
constructor(){
super();
this.state = {value: ''}
}
unCheck(i){
let ref = 'ref_' + i;
this.refs[ref].checked = !this.refs[ref].checked;
}
render(){
return (
<div>
{[1,2,3,4,5].map((item,i) => {
return (
<div>
<input type="checkbox" checked={true} ref={'ref_' + i}/>
<button onClick={()=>this.unCheck(i)}>Toggle</button>
</div>
)
})}
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<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='app'/>
Check this example of controlled element, means storing the state of checkbox inside state variable, and on click of button change the value of that:
class App extends React.Component{
constructor(){
super();
this.state = {value: []}
}
onChange(e, i){
let value = this.state.value.slice();
value[i] = e.target.checked;
this.setState({value})
}
unCheck(i){
let value = this.state.value.slice();
value[i] = !value[i];
this.setState({value})
}
render(){
return (
<div>
{[1,2,3,4,5].map((item,i) => {
return (
<div>
<input checked={this.state.value[i]} type="checkbox" onChange={(e) => this.onChange(e, i)}/>
<button onClick={()=>this.unCheck(i)}>Toggle</button>
</div>
)
})}
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<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='app'/>
React
Checked
Using State
<input type="radio" name="count" value="minus" onChange={this.handleRadioChange} checked={this.state.operation == "minus"} /> Decrement
2.Using Refs
<input type="radio" name="count" ref="minus" /> Decrement
onSubmit(e){ this.refs.minus.checked = false }
Using plain javascript you can acheive like below.
function unCheck() {
var x = document.getElementsByClassName("checkbox");
for(i=0; i<=x.length; i++) {
x[i].checked = false;
}
}
Small DEMO
I was thinking of a thing like that:
<input onChange={(input) => this.onFilterChange(input)} className="form-check-input" type="checkbox" />
onFilterChange = (input) => { let { value, checked } = input.target;}
unCkeckAll = () => {
[...document.querySelectorAll('.form-check-input')].map((input) => {
if (input.checked) {
let fakeInput = {
target: {
value: input.value,
checked: false
}
}
input.checked = !input.checked;
this.onFilterChange(fakeInput);
}
return null;
})
}
Checkboxes have a checked property, you can hook it to the state and change it dynamically. Check these links:
https://facebook.github.io/react/docs/forms.html#handling-multiple-inputs
http://react.tips/checkboxes-in-react/
Sometime its good to use plain javascript. If you have of checkbox value in any of your state then try this
let checkboxValue = xyz
document.querySelectorAll("input[value="+checkboxValue+"]")[0].checked = false;

React - Can't Uncheck Radio Button

I don't know what I'm doing wrong, but I'm unable to uncheck current radio button or select other radio buttons.
Basically, I have a table of occupants' details and I want to be able to indicate one of them as primary. The values are stored and retrieved in an mysql db. I am relatively new to ReactJS.
var PrimaryOccupantInput = React.createClass({
getInitialState: function()
{
return {
primary_occupant: (!(this.props.primary_occupant == null || this.props.primary_occupant == false))
};
},
primaryOccupantClicked: function()
{
this.setState({
primary_occupant: this.state.primary_occupant
});
this.props.primaryOccupantClicked(this.props.booking_occupant_id, this.state.primary_occupant.checked);
},
render: function() {
var is_primary = "";
if(this.state.primary_occupant != null)
{
if(this.state.primary_occupant == true)
{
is_primary = <span className="text-success">Yes</span>;
}
else if(this.state.primary_occupant == false)
{
is_primary = <span className="text-danger">No</span>;
}
else
{
is_primary = this.state.primary_occupant;
}
}
else
{
is_primary = <span className="text-muted"><em>undefined</em></span>;
}
return (
<div>
<input type="radio" id="primary_occupant" name="primary_occupant[]" ref="primaryOccupantCheckbox" checked={this.state.primary_occupant} onChange={this.primaryOccupantClicked} /> |
{is_primary}
</div>
);
}
});
onChange handler primaryOccupantClicked is basically a toggle function, so you want to set state opposite to current state (i.e. !this.state.primary_occupant). This will fix the issue:
primaryOccupantClicked: function()
{
this.setState({
primary_occupant: !this.state.primary_occupant
});
this.props.primaryOccupantClicked(this.props.booking_occupant_id, this.state.primary_occupant.checked);
},

Categories

Resources