JS Array access by index changes value to all indexes - javascript

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.

Related

How to add data in array on local storage?

I wanted to save data in local storage in form of array.
the first item is adding successfully but when i try to ad second item it replace item 1
this is my script file
function store(title, description) {
let titl = JSON.parse(localStorage.getItem("titl"));
let descriptio = JSON.parse(localStorage.getItem("descriptio"));
if (titl == null) {
t = [title];
localStorage.setItem("titl", JSON.stringify(t));
} else {
t = [title]
titl.push(t);
}
if (descriptio == null) {
d = [description];
localStorage.setItem("descriptio", JSON.stringify(d));
} else {
d = [description];
titl.push(d);
}
}
you dont update localstorage for the second values, and your pushing an array with a value onto an array (i think you just want to push a value onto the array)?
I think something like this is what your trying to acheive?
function store(title, description) {
// load the existing values (default to an empty array if not exist)
let _title = JSON.parse(localStorage.getItem("title") || "[]")
let _description = JSON.parse(localStorage.getItem("description") || "[]")
// add the new items
_title.push(title)
_description.push(description)
// update stored values
localStorage.setItem("title", JSON.stringify(_title)
localStorage.setItem("description", JSON.stringify(_description)
}

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

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.

Passing array value between two different click events

How can I pass values ​​from an array from one event click to another with jQuery?
Here is an example of I want to do: the first click event adds or remove values from the array if the input checkbox is selected or not. In the second click I want to loop trough all the elements of this array.
var array=[];
$( "input" ).on( "click", function() {
var $input=$(this)
if($input.is(":checked")){
array.push($(this).val()); //append check box value to array if is selected
}
else{
array.pop($(this).val()); // remove check box value to array if is not selected
}
})
$('#cmd').click(function() {
for (i of array) {
console.log(array[i]); // loop trough all elements in array
...
});
Your code looks ok except two things. First for for (i of array). Using of will return actual value as i, but you are using value as index in array[i].
If you want use index then use for (let i = 0; i < array.length; i++) instead.
You can also use Array.prototype.forEach() but you can't break out of it's loop https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Second thing is that .pop() doesn't support parameter. Use code below instead of .pop()
var index = array.indexOf($input.val());
if (index > -1) {
array.splice(index, 1);
}
If your event handlers are in different scope and #cmd handler can't see the array. You might use this little bit bad solution for sharing the array between scopes :)
$("input").on( "click", function() {
var array = $("#cmd").data("arr") || [];
var $input= $(this);
var value = $input.val();
if($input.is(":checked")){
array.push(value); /
} else {
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
}
$("#cmd").data("arr", array);
});
$('#cmd').click(function() {
var array = $(this).data("arr") || [];
for (let value of array) {
console.log(value); // loop trough all elements in array
}
});

Remove a specific filter in a Kendo Grid with toolbar template

I have a Telerik Kendo Grid with a toolbar template for create personalized filters.
I have 2 dropdownlist in my toolbar and the value selection must work in "And" with all filters (including the default filter of the grid).
When i want remove a filter i use this function:
CODE
<script type="text/javascript">
function removeFilter(filter, searchFor) {
if (filter == null)
return [];
for (var x = 0; x < filter.length; x++) {
if (filter[x].filters != null && filter[x].filters.length >= 0) {
if (filter[x].filters.length == 0) {
filter.splice(x, 1);
return removeFilter(filter, searchFor);
}
filter[x].filters = removeFilter(filter[x].filters, searchFor);
}
else {
if (filter[x].field == searchFor) {
filter.splice(x, 1);
return removeFilter(filter, searchFor);
}
}
}
return filter;
}
</script>
My problem is that my function removeFilter remove all the filters in my gridview when instead I would remove only the specific field.
I reproduce an Example in jsfiddle.
QUESTION
What's the correct method for delete only a specific field from the filters of the grid?
REFERENCES
GRID / Toolbar template
remove filter by name of the filed
function removefilter(filterField)
{
//grid id
var gridData = $("#your grid id").data("kendoGrid");
// get currently applied filters from the Grid.
var currFilterObj = gridData.dataSource.filter();
// get current set of filters, which is supposed to be array.
// if the oject we obtained above is null/undefined, set this to an empty array
var currentFilters = currFilterObj ? currFilterObj.filters : [];
// iterate over current filters array. if a filter for "filterField" is already
// remove filter by filed name
if (currentFilters && currentFilters.length > 0) {
for (var i = 0; i < currentFilters.length; i++) {
// for(var j=0; j<)
if (currentFilters[i].field == filterField) {
currentFilters.splice(i, 1);
break;
}
}
}
gridData.dataSource.filter({
logic: "and",
filters: currentFilters
});
}
add filter
function applyFilter(filterField, filterValue) {
// your grid id
var gridData = $("#grid id").data("kendoGrid");
// get currently applied filters from the Grid.
var currFilterObj = gridData.dataSource.filter();
// get current set of filters, which is supposed to be array.
// if the oject we obtained above is null/undefined, set this to an empty array
var currentFilters = currFilterObj ? currFilterObj.filters : [];
// iterate over current filters array. if a filter for "filterField" is already
// defined, remove it from the array
// once an entry is removed, we stop looking at the rest of the array.
if (currentFilters && currentFilters.length > 0) {
for (var i = 0; i < currentFilters.length; i++) {
if (currentFilters[i].field == filterField) {
currentFilters.splice(i, 1);
break;
}
}
}
// if "filterValue" is "0", meaning "-- select --" option is selected, we don't
// do any further processing. That will be equivalent of removing the filter.
// if a filterValue is selected, we add a new object to the currentFilters array.
if (filterValue != "0") {
currentFilters.push({
field: filterField,
operator: "eq",
value: filterValue
});
}
debugger;
// finally, the currentFilters array is applied back to the Grid, using "and" logic.
gridData.dataSource.filter({
logic: "and",
filters: currentFilters
});
}
based on this enter link description here
Your mistake is in myFilterChange function. You add filter on change but never remove the previous one. In the result of this you have condition like idcat == 1 && idcat == 2 after second change of this combo box.
You should clean filter before add another for the same column fiddle:
if (statoFilterValue) {
removeFilter(currFilters.filters, "idstate");
currFilters.filters.push({ field: "idstate", operator: "eq", value: parseInt(statoFilterValue) });
} else {
removeFilter(currFilters.filters, "idstate");
}
Also in removeFilter function you shouldn't use recursion in combination with splice. It is enough to asigne the result of splice
if (filter[x].filters.length == 0) {
console.log('empty');
filter = filter.splice(x, 1);
}

Javascript refresh array

I am using ajax to call DB and using DOM to create the HTML for a small weather widget.
So I have an Array of element called _weather.
Its populate fine, however I am having touble to refresh the data in the array.
I have a button that if clicked call this function and pass the city name _town
My idea is to remove the value from array and call the function _checkNewTown to display the city I just removed from the array.
var _update_city = function(_town){
ntown = _town;
town = _town;
_weather.prototype.removeByValue = function (town) {
for (var i = 0; i < this.length; i++) {
var c = this[i];
if (c == town || (town.equals && town.equals(c))) {
this.splice(i, 1);
break;
}
}
};
_checkNewTown(ntown);
}
However its not working and its returning
SCRIPT5007: Unable to set value of the property 'removeByValue': object is null or undefined
weather_widget.js, line 121 character 3
I tried change it but could not figure out what to use.
Any help will be apprecciated
You can use Array.prototype.filter to remove items from an array like so:
var weather = [{city: 'city1', ....}, ....];
var city = 'city1';
var filtered = weather.filter(function (i) {
return i.city !== city;
});

Categories