How to remove "Fruit" value from my text input area - javascript

So i need to remove the value that i added at the text input area as a chip, but i dont know how to solve the codes to link the it together and remove it. So what should happen is when the proper codes are linked together, it should be able to be removed when i click the "x" on the chip.
i'm able to add the values, but when i click remove the values are still there.
add(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
console.log(`mat chip`, event);
console.log(`mat chip value`, value);
// Add our fruit
if ((value || '').trim()) {
this.fruits.push({name: value.trim()});
console.log(`fruits`, this.fruits);
let type = this.editDeliveryOrderForm.value.type;
type += ',' + value.trim();
this.editDeliveryOrderForm.patchValue({
type
});
}
// Reset the input value
if (input) {
input.value = '';
}
}
remove(fruit: Fruit): void {
const index = this.fruits.indexOf(fruit);
const value = fruit.name;
// console.log(`mat chip`, event);
// console.log(`mat chip value`, value);
if (index >= 0) {
this.fruits.splice(index, 1);
// this.fruits.push({name: value.trim()});
// console.log(`fruits`, this.fruits);
let type = this.editDeliveryOrderForm.value.type;
value.trim();
this.editDeliveryOrderForm.patchValue({
type
});
}

Array method indexOf() is case sensitive. The object which passed to fruits array does not return the index.
const index = this.fruits.indexOf(fruit);
//console.log(index);
if(index !== -1) {
// code..
}

You can use Array.filter() to filter the elements in array
remove(fruit: Fruit): void {
this.fruits = this.fruits.filter((fr)=>fr.name !== fruit.name);
}
This will return new array removing the current fruit.

Related

JS Array access by index changes value to all indexes

I'm trying to change array item value by index on DOM Event.
When the array have few items initially it works fine but when it's initialized empty and I add item to it, modify it's value. Every single item added after that copies the same value. Other case, when added N items in initially empty array, if I change value by index arr[x] it changes all elements values.
function GetIndex(listBox, selectedFieldName) {
var index = 0;
if (listBox == 'selected') {
index = selectedFields.findIndex(x => x.fieldName == selectedFieldName);
}
else if (listBox == 'optional') {
index = optionalFields.findIndex(x => x.fieldName == selectedFieldName);
}
return index;
}
function SetCurrentValue() {
if (changedField != '') {
var index = GetIndex('selected', changedField);
selectedFields[index].attributes.displayName = $('#display-name').val();
selectedFields[index].attributes.defaultValue = $('#default-value').val();
selectedFields[index].attributes.editable = $('#editable').is(":checked");
selectedFields[index].attributes.required = $('#required').is(":checked");
selectedFields[index].attributes.hidden = $('#hidden').is(":checked");
selectedFields[index].attributes.isId = $('#is-id').is(":checked");
selectedFields[index].attributes.hyperLink = $('#hyper-link').is(":checked");
selectedFields[index].attributes.dateFilter = $('#date-filter').is(":checked");
selectedFields[index].attributes.wholeNumber = $('#whole-number').is(":checked");
selectedFields[index].attributes.multiLineTextBox = $('#multilinetext-box').is(":checked");
}
}
I've checked it gets the correct index and correct item. This function setCurrentValue is called once onChange() event and if I add 60 new items they are all with the same value.

Why does findIndex() return 0, instead of the desired index?

I've been stuck trying to figure out how to retrieve a desired index. I have a user adding names to a Guestlist, with the option to remove names. All the names are appended to an array saved to localStorage. When the delete button is clicked, I want to iterate over the array, find the matching string and retrieve it's index. All I'm getting however, is a -1 if the string doesn't match, and 0 if it matches. Where is my error? Any help is appreciated.
deleteBtn.addEventListener('click', function () { // Makes the Delete button active.
const deleteName = this.parentElement.innerText; // parent element is li
const test = localStorage.getItem('data');
const testParsed = JSON.parse(test);
for (let i = 0; i < testParsed.length; i++) {
let compare = `Name: ${testParsed[i].name}, About: ${testParsed[i].about}Delete entry`; // matches innerHtml of deleteName
compare.replace('.,:', ''); // Removes unwanted punctuation
console.log('Compare: ', compare);
function index(){
return deleteName === compare;
}
console.log(testParsed.findIndex(index));
I played around some more, and figured it out. I'll leave the question up in case someone else can make use of it.
deleteBtn.addEventListener('click', function () { // Makes the Delete button active.
const deleteName = this.parentElement.innerText; // parent element is li
const test = localStorage.getItem('data');
const testParsed = JSON.parse(test);
console.log(test);
for (let i = 0; i < testParsed.length; i++) {
let compare = `Name: ${testParsed[i].name}, About: ${testParsed[i].about}Delete entry`; // matches innerHtml of deleteName
compare.replace('.,:', ''); // Removes unwanted punctuation
console.log('Compare: ', compare);
if(deleteName === compare) {
function index(equals) { // compare is string, equals is object
return equals.name === testParsed[i].name && equals.about === testParsed[i].about;
}
console.log(testParsed.findIndex(index));
}

How to use hooks in Handsontable. I need check data before paste

I need to check the data before inserting it into the table and if it is not correct, change it and insert it. I'm trying to create a hook with a beforeInsert prefix and describe this logic there, but it doesn't work.
I tried this code for testing, but nothing changes when pasting
hot1.addHook('beforePaste', function(td1, row1, col1, prop1, value1, cellProperties1) {
if (prop1 === 'cost1') {
var cellMeta1 = this.getCellMeta(row, this.propToCol('cost2'));
cellMeta1.type = 'text';
cellMeta1.source = 'hello';
}
}
);
Could the problem be that before that I call this hook?
hot1.addHook('beforeRenderer', function(td, row, col, prop, value, cellProperties) {
if (prop === 'warehouse') {
var cellMeta = this.getCellMeta(row, this.propToCol('xWarehouse'));
cellMeta.readOnly = (value != ' ' && value != '' && value != null) ? true : false;
}
}
);
How can you check and insert the changed value into the table?
Example:
At input 3 213, insert 3213, just remove the spaces
UPD :
I also tried to use this:
if (prop === 'cost1' && value != '') {
var cellMeta = this.getCellMeta(row, this.propToCol('cost1'));
hot1.setDataAtCell(row,col,value);
}
});
But in this case, my table freezes
We can change the value with afterChange hook.
var setter = false;
hot1.addHook('afterChange', function(changes, src) {
if (!setter) {
setter = true;
for(let obj of changes){
var currentRow = obj[0];
var currentValue = obj[3].replace(/\s+/g,'');
var currentCol = obj[1].replace(/\s+/g,'');
var colNumber = hot1.propToCol(currentCol);
hot1.setDataAtCell(currentRow, colNumber, currentValue);
}
} else {
setter = false;
}
});
Handsontable will substitute the values ​​of changes and src itself, after which we can pull out the inserted value and change it, and then insert it back

Using localStorage trying to set an array value not able to update or delete array value

I have to select few elements from UI and then need to store the id of each selected in the localstorage. When user will deselect it , then that value from localstorage should also be removed . for that which I did
#observable marks = JSON.parse(localStorage.getItem('marks')) || [];
#action handleChange = Mid => {
let getMarks = JSON.parse(localStorage.getItem('marks')) || [];
let foundIndex = getMarks.indexOf(Mid)
if (foundIndex > -1) {
remove(getMarks, id => id === Mid)
} else {
localStorage.setItem('marks', JSON.stringify([Mid]))
}
}
Here, localStorage adds the only recent value and while and also not getting set to the observable which I am using it to render .
How do I fix this ?
Thanks.
Updated fix
#action handleChange = Mid => {
let foundIndex = this.marks.indexOf(Mid)
if (foundIndex > -1) {
remove(this.marks, id => id === Mid)
localStorage.setItem('marks', JSON.stringify(this.marks))
} else {
this.marks.push(Mid)
localStorage.setItem('marks', JSON.stringify(this.Mid))
}
}
To add new item you want to push it into the existing array. Instead you are creating a new array with one element and ignoring anything that was previously stored
Change:
localStorage.setItem('marks', JSON.stringify([Mid]))
To
getMarks.push(Mid)
localStorage.setItem('marks', JSON.stringify(getMarks))

Deleting objects stored in formData based on attribute other than key

I am storing files into formData like such:
formData.append("images[]", file)
formData.append("images[]", file_2)
formData.append("images[]", file_3)
I know it's possible to delete the files using formData.delete(), but in this case, since all of the keys are the same, how do I specifically delete the object where the value is for example, file_2?
Not sure if this is the optimal way. But you can get all values using getAll. Then filter and append once again. Demo.
const form = new FormData
form.append('names[]', 'Chris')
form.append('names[]', 'Bob')
form.append('names[]', 'John')
console.log(Array.from(form.entries()))
const names = form.getAll('names[]')
form.delete('names[]')
names
.filter(name => name !== 'Bob')
.forEach(name => form.append('names[]', name))
console.log(Array.from(form.entries()))
The function getAll() returns an array containing all values of a specific key.
var values = formData.getAll("images[]");
Then you can delete a specific value from the array and set the modified array as new value.
var index = values.indexOf(file_2); //only necessary if you dont know the index
values.splice(index, 1);
formData.set("images[]", values);
/* Add index */
formData.append("images[0]", file)
formData.append("images[1]", file_2)
formData.append("images[2]", file_3)
/* Remove by index */
formData.delete(`images[${index}]`)
This works pretty fine!
// just a generic function to help you removing an element at specific position
function removeAt(array, index) {
try {
const length = array.length;
if (index <= 0)
return array.slice(1);
if (index >= length - 1)
return array.slice(0, length - 1);
return array.slice(0, index).concat(array.slice(index + 1));
} catch(err) {
console.warn(err);
}
return null;
}
const currentValue = myFormData.getAll('someKey');
myFormData.delete('someKey');
for (const i of removeAt(currentValue, index)) {
myFormData.append('someKey', i);
}

Categories