views:

68

answers:

4

This is driving me crazy. Please someone tell me I'm not crazy:

var constraints = $('.traffic-constraints :input');
console.log(constraints);

var i;
for (i = 0; i < constraints.length; i++) {
  if (constraints[i].val() > 0) { //<-------- errorrzz
....

the console tells me that i do, in fact, have input objects in my selector (5 of them). however, i get the following error: constraints[i].val is not a function

wtf?

A: 

Why don't you use each?

metrobalderas
i could, but it's a bit slower... what is wrong with what i'm doing?
Jason
If it works though, I wouldn't be too upset at it being slower.
alex
i would still like to know for learning's sake what i'm doing wrong here
Jason
for what it's worth, i didn't downvote you
Jason
+1  A: 

jQuery has an .each() method to loop through the elements of a collection. You can use it as such:

$('.traffic-constraints :input').each(function(index) {
    if($(this).val() > 0) {
       doSomething();
    }
});

The reason why your loop isn't working is that the elements are not extended with jQuery's methods. The following fixes it:

var constraints = $('.traffic-constraints :input');
console.log(constraints);

var i;
for (i = 0; i < constraints.length; i++) {
    if ($(constraints[i]).val() > 0) {
        doSomething();
    }
}

But for reasons of code maintainability and best practices, use .each(). It isn't noticeably slower and is easier to maintain and understand.

Andrew Moore
thanks.. yeah i forgot to wrap it in $()
Jason
+2  A: 

First, use .each() it's easier :)

But, to answer the question why doesn't it work...you're dealing with a dom element with that index, you need to wrap it or .eq(i) acesss it:

for (i = 0; i < constraints.length; i++) {
  if ($(constraints[i]).val() > 0) {

Or (better, but still use .each()!):

for (i = 0; i < constraints.length; i++) {
  if (constraints.eq(i).val() > 0) {
Nick Craver
thanks... i figured this out the second before you posted this!
Jason
+1  A: 

Accessing elements like that (e.g. $('.traffic-constraints :input')[0]) returns the HTML element (or DOM node, to be more pedantic). If you want to get the element jQuery-wrapped, call constraints.eq (i)

K Prime