Trying to output separate click functions with jquery based on a array - javascript

I have this array that is auto generated based on images in a gallery. I need to give them all seperate click events that output variables from another array on click so I can pass them into a string that is attached to the end of a url to submit to pinterest. The part that is slipping me up is the click event,
Here is the code, so far it just alerts last part of the array and does it twice, I want each click to alert seperately the first array for the first click, and the second array position for the second clicked.
THis is the corresponding array console.logged, it is the individual classes for different buttons to click.
[".btnPinIt , 0", ".btnPinIt , 1"]
for (var j = 1; j < clickArray.length; j++){
console.log(clickArray[j]);
$(clickArray[j]).click(function() {
alert(j);
});
}

One problem is your j is in the same scope for all handlers, so has a value of clickArray.length when the click occurs, but you should not need separate handlers for this. Use data attributes on the elements and pick them up from a single handler.
Another is that you are indexing the array from 1 instead of 0.
You also need an array that has valid selectors as, at the moment, you have an array of invalid jQuery selectors.
e.g. Assuming you have an array of id selectors:
clickArray = ["#btnPinIt1",
"#btnPinIt2"]
// save the index values on the elements
for (var j = 0; j < clickArray.length; j++){
$(clickArray[j]).attr('data-val', j+1);
}
// Use a startswith selector (in this example) to handle the clicks
$("[id^=btnPinIt]").click(function() {
alert($(this).data('val'));
});
Simpler still would be to use your class and index them in order from 1 to n:
$('.btnPinIt').each(function(e, i){
$(this).attr('data-val', i+1);
}).click(function() {
alert($(this).data('val'));
});
This also chains the click and each.

Related

Executing too commands withing the same loop

I have this piece of code:
for (var i = 0, row; row = document.getElementById("myTbl").rows[i]; i++) {
row.cells[headCatg.cellIndex].classList.remove("red");
row.deleteCell(headCatg.cellIndex);
}
I need to remove the class "red" from each cell of the table column and then delete that column. The reason I need to remove class first, because it has been added to DOM by another cript and if I remove the column the class just appears in the next column.
When I run each of these commands (remove() and deleteCell()) individually in the loop, everything seem to work fine, but when I put them together, the column is removed but the class shifts to another column.
What am I missing?
You have to convert the HTMLcollection to an array
The reason why your code wasn't working properly it's because HTMLcollection returns a live NodeList which means when you use remove on each element in the collection the other elements gets rearranged and the length of the list get's smaller causing you to skip some of them so you should convert your html collection to an array using Array.from
row = document.getElementByClassName("myTbl")
rowarr=Array.from(row)
for (var i = 0, rowarr.length; i++) {
row[i].cells[headCatg.cellIndex].classList.remove("red");
row[i].deleteCell(headCatg.cellIndex);
}

Updating an array based on randomly generated index

I'm very new to Javascript and jQuery. I'm trying to create a film list that will randomly pick an item from the list, post the result, and remove the item from the original list. It uses text input, .push and .append to keep track of the list and update an array of matching text. My thinking was that I would use an array that matches the ul to generate a random index number from its length and then use the number to remove the li from the ul by index. The basic idea is working. My issue is that every time it selects an item from the list, the item it removes from the array is different than the item it posts and removes from the ul. The parts seem to work fine separately until I run them in a function together tied to a button.
Here is the code I'm using. The watchList array is populated with a .push whenever text is accepted to update the ul. I've checked and the index for both match up.
function randomShow(){
var r = Math.floor(Math.random() * watchList.length);
for(var i = 0; i < watchList.length; i++){
if(i === r) {
alert(watchList[i]);
watchList.splice(watchList.indexOf[i],1);
$("li").eq(i).remove();
}
}
}
I think you don’t need a loop. Try this;
function randomShow(){
var r = Math.floor(Math.random() *watchList.length);
$("li").eq(r).remove();
}

How to remove elements inside specified index of array using angular

I need to remove some elements inside an array with specified index. I am trying to use slice function for it but it is giving me undefined error.
This is my controller code:
if($scope.startColm<$scope.endColm){
//Suppose here startColm value is 1 and endColm value is 4
for(var j=0;j<rowCellData.length;j++){
//rowCellData is an array. Attaching its image for reference
for(var k=$scope.startColm;k<($scope.endColm-$scope.startColm);k++){
var cellData=rowCellData[j].slice($scope.startColm,$scope.endColm)
//Here i want to remove data inside rowCellData from specified index.
}
}
}
rowCellData consists data like this:
Inside each index there is some data which I need to fetch based on the specified startColm and endColm value. Like here i want the data from 1st to 4th position for all the index of rowCellData.
Please suggest how to remove data inside array elements.
You want the 'splice' method, not the 'slice' method. However, since you have objects inside the main array and not other arrays, you could use delete to remove the items:
for (var i = $scope.startColm; i <= $scope.endColm; i++) {
delete rowCellData[j][i]
}

AngularJs pushing multiple values from array to another with databinding refreshing

I am getting an array from the server which can contain 0..n elements in an array. I then add that to array I use locally for databinding (basically cache data in client). When doing it this way databiding works without any problems:
for (var i = 0 ; i < data.Result.length ; i++) {
scope.cachedData.push(data.Result[i]);
}
Meaning - view refreshes, everything works. But when I try: scope.cachedData.concat(data.Result); it won't work. Why is that?
If you want to push everything in a single instruction use apply without breaking the reference to scope.cachedData
Array.prototype.push.apply(scope.cachedData, data.Result);
Also, I know this is a little bit off topic but if you want to insert at a specific index you can use splice with apply
// I definitely want to prepend to my array here
var insertionIndex = 0,
// we don't want to delete any elements here from insertionIndex
deleteCount = 0;
// Because we use apply the second argument is an array
// and because splice signature is (startIndex, noOfElementsToDelete, elementsToInsert)
// we need to build it
Array.prototype.splice.apply(scope.cachedData, [insertionIndex, deleteCount].concat(data.Result));
Imagine your array scope.cachedData = [3,4]; and data.Result = [1,2];, with the code above scope.cachedData will become [1,2,3,4].

splice() not updating items order of array within knockout.js

Following a prior post on how to update the order of an array. I followed the suggestion of Michael Best and used splice() to modify the ordering of my array on button click
self.moveup = function (itemIndex) {
var i = self.itemList.indexOf(itemIndex);
if(i >= 1){
var array = self.itemList();
self.itemList.splice(i-1, 2, array[i], array[i-1]);
}
Where I am having trouble is in incrementing the items in the array. From reading the usage of Array Splice The first param indicates where the change should occur for moving up I would think that would be i+1 , the value 2 indicates how many items in the array would change so no change there and then the range I thought would be the selected item array[i] and the end would be [i+1] as I am increasing the position.
self.itemList.splice(i+1, 2, array[i], array[i+1]);
In the attached fiddler you can see the values increase but the items do not actually change order they are only replicating when you hit the down button. I expected the result to be the same as when calling moveUp.
I'd appreciate any pointers on what I am missing here. http://jsfiddle.net/rlcrews/SCWmk/5/
-cheers
Almost there. Here's how I did it.
When moving an item up, you need to swap it with the previous item. Thus, you need to replace the elements at indices i-1 and i with array[i] and array[i-1], respectively. Your moveup method does exactly that, so all is good.
Now, when moving an item down, you need to swap it with the next item. Thus, you replace the elements at indices i and i+1 with array[i+1] and array[i], respectively. Your code however changes the elements i+1 and i+2, which is no good. Instead, you should be doing:
self.itemList.splice(i, 2, array[i+1], array[i]);
You start splicing at i (as you're removing the elements at i and i+1) and you replace them (insert at that index) with array[i+1] and array[i].
On another note, your check for whether you can move the item down is incorrect. The only item you should not move down is the last item, i.e. the element at index self.itemList().length-1. Thus, the check should look like if (i < array.length - 1) { ... } (see the fiddle).

Categories

Resources