Add and Remove Values Inside Array in Change Event of Checkbox

Add and remove values inside array in change event of checkbox

Change to (ngModelChange)="getCheckboxValues($event,item)"

and the function to add if not there and remove if the element exist based on check and uncheck of checkbox

  //Checkbox Change detecting function
getCheckboxValues(ev, data) {
let obj = {
"order" : data
}

if(ev.target.checked){
// Pushing the object into array
this.newArray.push(obj);

}else {
let removeIndex = this.newArray.findIndex(itm => itm.order===data);

if(removeIndex !== -1)
this.newArray.splice(removeIndex,1);
}

//Duplicates the obj if we uncheck it
//How to remove the value from array if we uncheck it
console.log(this.newArray);
}

Link https://stackblitz.com/edit/angular-5jamcr

checkbox value array add and remove from array

Answer: http://jsfiddle.net/morrison/S3e2f/

Notes:

  • Use a key/value system. This way you can know which array item to set or unset. This probably means giving your checkboxes names.
  • Don't loop over the array each time every time something changes. That's bad design and could lead to bad performance. I restructured the HTML.

@click on checkbox add/remove data

This is a built-in behavior of v-model when used with an array on multiple checkboxes. You don't need a click handler. (Code shamelessly lifted from Bert's answer.)

console.clear()
new Vue({ el: "#app", data:{ selectedAddOns:[], categories:[ { addOns:[ {name: "AddOn One", price: 10}, {name: "AddOn two", price: 20}, {name: "AddOn Three", price: 30}, ] },
], categoryId: 0 }})
<script src="https://unpkg.com/vue@2.4.2"></script><div id="app">  Selected Addons: {{selectedAddOns}}  <div class="col-6" v-for="addOn, index in categories[categoryId].addOns">    <label class="custom-control custom-checkbox" >        <input type="checkbox" class="custom-control-input" :value="index" v-model="selectedAddOns" >        <span class="custom-control-indicator"></span>        <span class="custom-control-description">{{ addOn.name }} (+ ${{ addOn.price }})</span>    </label></div></div>

how to add/remove data to state depending on if the checkbox was checked and then unchecked

If I'm understanding your question you basically want to add the id if checked is true, and remove the id if checked is false, from the dayId state. In setDayId check the checked value and if true then shallow copy the dayId state and append the new id (value), otherwise remove it from the dayId array using a .filter function.

{days.map((day, idx) => (
<input
onChange={(e) => {
const { checked, value } = e.target;

setDays(
days => days.map(data => {
if (data.id === day.id) {
return {
...data,
id: value,
select: !data.select,
};
}
return data;
})
);

setDayId(prev => {
return checked
? [...prev, value] // add if checked
: prev.filter(val => val !== value) // remove if not checked
});

console.log("CHECKING CHECKED VALUE", e.target.checked);
console.log("WHAT IS THE SET VALUE", values)
}}
key={idx}
name={day?.name}
type="checkbox"
value={day?.id}
checked={day.select}
/>
))}

How to add and remove values from local storage on checkbox click in Angular8

Updated:

setColumn($event, item) {
let valueAliasPair = JSON.parse(localStorage.getItem("AvailableAmt") || "[]");

if (item.tabelHeader.data != "") {
if ($event.checked) {
valueAliasPair.push({
key: item.tabelHeader.data,
value: true,
});
localStorage.setItem("AvailableAmt", JSON.stringify(valueAliasPair));
} else {
const ind = valueAliasPair.findIndex((x) => x.key === item.tabelHeader.data);
valueAliasPair.splice(ind, 1);
localStorage.setItem("AvailableAmt", JSON.stringify(valueAliasPair));
}
}

console.log(valueAliasPair, "valueAliasPair");
}

Add or Remove clicked Item from the Array list

Just push the element to array, if the element doesnot exist in array.

If the element already exist, remove it from array using Array.splice

I have moved the click even from the li to the input.

Also I have used flex display for the elements, so that the label can use the remaining space in the li

const created = [];
function theFunction(event) {
const index = created.indexOf(event.target.value);
index === -1 ? created.push(event.target.value) : created.splice(index, 1);
console.log(created);
}
li {
display: flex;
}

label {
flex: 1;
}
<ul class="dropdown-menu" id="userlist">
<li class="list-group-item border-0 py-2" id="first-wrapper">
<input class="form-check-input me-1" type="checkbox" value="first" id="first" onclick="theFunction(event)">
<label for="first">First checkbox</label>
</li>
<li class="list-group-item border-0 py-2" id="second-wrapper">
<input class="form-check-input me-1" type="checkbox" value="second" id="second" onclick="theFunction(event)">
<label for="second">Second checkbox</label>
</li>
<li class="list-group-item border-0 py-2" id="third-wrapper">
<input class="form-check-input me-1" type="checkbox" value="third" id="third" onclick="theFunction(event)">
<label for="third">Third checkbox</label>
</li>
<li class="list-group-item border-0 py-2" id="fourth-wrapper">
<input class="form-check-input me-1" type="checkbox" value="fourth" id="fourth" onclick="theFunction(event)">
<label for="fourth">Fourth checkbox</label>
</li>
<li class="list-group-item border-0 py-2" id="fifth-wrapper">
<input class="form-check-input me-1" type="checkbox" value="fifth" id="fifth" onclick="theFunction(event)">
<label for="fifth">Fifth checkbox</label>
</li>
</ul>

How to remove element after unchecking the checkbox from the array?

The way you are getting the checked needs to change

_handleChartSelection(chartId, e){
var checked = e.target.checked;
let data = this.state.selectedChartId
if(checked)
data.push(chartId);
else{
let i = data.indexOf(chartId);
data.splice(i,1);
}
this.setState({
selectedChartId: data
});
console.log(this.state.selectedChartId);
}

Please try this

uncheck (removing) last item in checkbox and check(adding) other at the same time , keeps the unchecked value and adds other checked value

Issue

You are mutating your assignCustomerId state and saving the same array reference back into state. When updating the "already assigned delivery persons" the code pushes directly into the assignCustomerId array. Also, when checked is true the code is pushing directly into the assignCustomerId array, and when checked is false the .splice does an in-place mutation

if (assignCustomerId.length === 0) {
for (let i = 0; i < alreadyAssignedDeliveryMan.length; i++) {
assignCustomerId.push(alreadyAssignedDeliveryMan[i]); // <-- state mutation!
}
} else {
console.log("null");
}

const checked = event.target.checked;
if (checked === true) {
assignCustomerId.push(id); // <-- state mutation!
setAssignCustomerId(assignCustomerId);
} else if (checked === false) {
for (var i = assignCustomerId.length - 1; i >= -1; i--) {
if (assignCustomerId[i] === id) {
assignCustomerId.splice(i, 1); // <-- state mutation!
setAssignCustomerId(assignCustomerId);
}
}
}
Solution

When adding a value to the assignCustomerId array create a shallow copy and append the new element value(s). When removing a value from the `assignCustomerId array then filter it and return a new array reference.

if (!assignCustomerId.length) {
setAssignCustomerId(state => state.concat(alreadyAssignedDeliveryMan));
} else {
console.log("null");
}

const { checked } = event.target;

if (checked) {
setAssignCustomerId(state => [...state, id]);
} else {
setAssignCustomerId(state => state.filter((el) => el !== id));
}


Related Topics



Leave a reply



Submit