Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery how does one peek ahead in each()?

I can't seem to find a definite answer for this. Consider the following:

var dupe = false;
    $(".syndUID").sort(function(a,b) {
        return a - b;
    }).each(function(i, el) {
        alert($(this).val() + " - " + $(this).next().val());
        if($(this).val() == $(this).next().val()) {
                dupe = true;
                return;
        };
    });

This code is an attempt to find duplicate values in a set of inputs with the class syndUID. They are scattered about a form, so not next to eachother in the DOM.

next().val() is always undefined though. am I using the wrong function? How do I simply peek ahead to the next element? I have access to the index, but I don't know how to even make use of it.

EDIT:

After reading the comments and answers I realized there really is no proper iterator in jQuery, which seems really stupid to me since it provides each(). I also had another bug with the above code. Here is the final solution I used that works:

// duplicate check
    var dupe = false;
    var prevVal = undefined;
    $(".syndUID").sort(function(a,b) {
        return $(a).val() - $(b).val();
    }).each(function() {
        if($(this).val() == prevVal) {
            dupe = true;
            return false;
        }
        prevVal = $(this).val();
    });

For anyone who finds this via google, the answers provided by others may be a decent alternative solution, but for my needs I found this sufficed.

like image 849
dmarra Avatar asked Dec 22 '15 17:12

dmarra


1 Answers

You can do something like $('.syndUID')[i+1] to regrab the list, focusing on that element (and optionally turning it back into a jQuery object)

Using [i+1] will return a DOM element, but you can use .eq(i+1) to return a jQuery object. Or if you hate your future developers, wrap the DOM element in $() because screw readability!

As Andreas stated -- regrabbing the list is wasting memory. Before the loop, cache the object into a variable with var element = $('.syndUID') so you're not iterating the DOM so much.

like image 187
Sterling Archer Avatar answered Sep 29 '22 09:09

Sterling Archer