Accessing the previous element in $('.class').each() - javascript

Is there a way to access the previous or next element while in a certain iteration of a $('.class').each() loop; Where the elements with class 'class' are not siblings?
I was able to do this by traversing through the DOM tree. But I was wondering if there is a more concrete and elegant solution.
Current code:
$('.slider-range').each(function(index){
var temp = $(this).closest('.panel').next('.panel').find('.slider-range');
//do something with temp
});

You will have to "store" the "selected" items in a variable and use the index passed to the callback like this:
var range = $('.slider-range');
range.each(function(index){
var temp = index > 0 ? range[index - 1] : null;
//do something with temp
});
I added a condition on the value of the index, to make the tempvariable null if index is 0.
Edit: Corrected with index - 1 to "select" the previous item.

In your loop, you have access to the current index within the collection of jquery objects.
$('.slider-range').each(function(index){
var temp = $(this).closest('.panel').next('.panel').find('.slider-range');
//do something with temp
});
You can use this to get any of the other items in that collection:
var items = $(".slider-range");
items.each(function(index) {
if (index > 0) {
var prev = items[index-1];
// do something with prev
}
});

Related

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
}
});

Traversing list items using array method

I am using the values input by the user to perform this action.
Here is the full code: https://jsfiddle.net/7196dfyz/
This is part of the code where the elements are traversed, where I'm having trouble:
var lists = $ul.getElementsByTagName("li");
for (var i = 0; i < lists.length; ++i) {
if (lists[i] == value) {
$("ul").css("background-color","black");
}
}
The first input should take the value in some li
and the second input should take the respective parent ul class name.
I think this is what you're looking for. (Here is an updated jsfiddle):
function func() {
var key = $("#key").val();
var value = $("#entry").val();
var $ul = $("." + key);
var lists = $ul.find("li");
for (var i = 0; i < lists.length; ++i) {
console.log($(lists[i]).text(), value);
if ($(lists[i]).text() === value) {
$(lists[i]).css("background-color","black");
}
}
}
You have several issues:
$ul.getElementsByTagName is not a valid function. Because $ul at this point is a jQuery array-like object, it wont work. You'd need to do $ul[0].getElementsByTagName, or simply use jQuery's find() like my example above.
You're trying to compare lists[i] to value, which happens to be an HTML element. When comparing to a string, it will return <li>Say</li> which will never match anything you type in. Using $(lists[i]).text() should get you what you need.
$("ul").css("background-color","black");: You were setting every ul to black if a match was found. I assume you only want to match the one that was matched. $(lists[i]).css("background-color","black"); fixes this.
You can even simplify this entire function down to this:
function func() {
var key = $("#key").val();
var value = $("#entry").val();
$("." + key).find("li").filter(function() {
return $(this).text() === value;
}).css("background-color","black");
}
Broken down:
$("." + key): Find the ul that has the class of key.
.find("li") Find all list items within each unordered list found.
.filter(...) For each element in this list, and return to me only the items that match my criteria: $(this).text() === value.
And finally .css("background-color","black"): Set all the background colors to black of the list items that were returned from the filter() function.

Remove item from array in JavaScript

Seen this question a lot, but cannot find something that's what i'm looking for.
onClick I push an item to an array I have, however, if there's 3 items in my array I don't want to be able to push items anymore.
var selectedData = [];
I set my empty variable.
var index = selectedData.indexOf(3);
I then get the index of my array which is 3
if (index > 3) {
selectedData.splice(index, 1);
}
Then within my if statement I say, if my index which is 3, is bigger then 3, then splice at index and remove one.
selectedData.push(TheThing);
I then push TheThing to my array if the if statement above isn't true.
However, I have a variable var arrayLength = selectedData.length; that grabs the length, and when I console log it, it starts at 0 and splices items anything after 4. Not 3.
Any idea what i've done wrong or misunderstood?
Thanks
More full example of my code
var selectedData = [];
myElement.on('click', function() {
var index = selectedData.indexOf(3);
if (index > 3) {
selectedData.splice(index, 1);
}
var arrayLength = selectedData.length;
console.log(arrayLength, 'the length');
});
So in short, onClick check my array and remove anything after the third that gets added into my array.
Do you want this to behave as a stack or a queue?
So your code here:
var index = selectedData.indexOf(3);
Is not grabbing the 3rd index - its grabbing the first index where it sees 3, or -1 if it doesn't. Replace your if statement with,
if (selectedData.length > 3) {
selectedData.pop() // removes last element (stack)
// or
selectedData = selectedData.slice(1) //remove first element (queue)
}
I think you need to try var arrayLength = selectedData.length -1;
You start at 0 like a normal array, but don't you start with an empty array?
Plus when you use .length, it returns the true count of the array or collection not a 0 index.
`
you can override push() method of your array like this:
var a = [];
a.push = function(){}
or like this
a.push = function (newEl){
if(this.length <3){
Array.prototype.push.call(this, newEl)
}
}
This is not complete example because push() can take many arguments and you should to handle this case too
var index = selectedData.indexOf(3); simply give you the index of the element of the array that has value 3
Example
selectedData = [ 0, 3 , 2];
alert( selectedData.indexOf( 3 ) ); // this will alert "1" that is the index of the element with value "3"
you can use this scenario
var selectedData = [];
myElement.on('click', function() {
//if selectedData length is less than 3, push items
});
This could work.
myElement.on('click', function() {
if(selectedData.length > 3){
selectedData = selectedData.splice(0, 3);
}
console.log(selectedData.length, 'the length');
});

grab the current index of the element from an Array

i have an image array like this
var bigImagesList = document.getElementsByClassName('monique-image');
Now i am trying to check if an image in an array is having current path like tis
for (var i = 0; i < bigImagesList.length; i++) {
if (bigImagesList[i].getAttribute('src') === currentBigImageFilePath) {
// Current Image Big Grab //
currentBigImageToDisplay = bigImagesList[i];
var currentIndex = bigImagesList[i].index;
console.log(currentIndex);
but somehow it says undefined . Please tell me how can i grab the index of the current item in if condition. thanks
When you are looping through the array, already you have the index there, as you are looping through the array of bigImagesList. So you might just need to replace:
var currentIndex = bigImagesList[i].index;
With:
var currentIndex = i;
You don't even need to create a new variable, IMO.

Add modifiers to duplicate elements in Lodash.js?

The input will be a list with duplicate elements like this:
['30','10','10','20','20','30']
And the output will be a list with modified elements like this:
['30#1', '10#1', '10#2', '20#1', '20#2', '30#2']
The # modifier indicates the time for this element to appear in the list..
Does anyone have ideas about this?
So you want the result to be an array with an item that corresponds to each item in the original array. That's a job for Array.prototype.map. You want to keep a running count of how many times each item has appeared, which you can do with a simple object. In every iteration you look up the number of times the item has appeared and add one. Store that number as the new count and use it to build your return value. Like this, more or less:
var arr = ['30', '10', '10', '20', '20', '30'];
var counts = {};
var arr2 = arr.map(function(item) {
counts[item] = (counts[item] || 0) + 1;
return item + "#" + counts[item];
});
You don't need Lodash for this at all.
Here's an example using lodash.
_.map(coll, function(item) {
return item + '#' +
_.set(this, item, _.get(this, item, 0) + 1)[item];
}, {});
What's nice is that you don't need to setup temporary variables here to compute your result. The idea is to store them in this - the empty object that's passed to map().
The get() function provides you with the 0 default if the property doesn't exist. So this can be used directly with set(), which sets the property value, and returns the object.
Example:
var count = {};
['30','10','10','20','20','30'].map(function(current) {
count[current] ? count[current] +=1 : count[current] = 1;
return current + '#' + count[current];
})

Categories