Correct use of a "for...in" loop in javascript?

Posted by jnkrois on Stack Overflow See other posts from Stack Overflow or by jnkrois
Published on 2010-06-07T19:02:39Z Indexed on 2010/06/07 19:12 UTC
Read the original article Hit count: 141

Filed under:

Hello everybody, before I ask my question I wanted to let everybody know that I appreciate the fact that there's always somebody out there willing to help, and on my end I'll try to give back to the community as much as I can. Thanks

Now, I would like to get some pointers as to how to properly take advantage of the "for...in" loop in JavaScript, I already did some research and tried a couple things but it is still not clear to me how to properly use it.

Let's say I have a random number of "select" tags in an HTML form, and I don't require the user to select an option for all of them, they can leave some untouched if they want. However I need to know if they selected none or at least one.

The way I'm trying to find out if the user selected any of them is by using the "for...in" loop. For example:

var allSelected = $("select option:selected");
var totalSelected = $("select option:selected").length;

The first variable produces an array of all the selected options. The second variable tells me how many selected options I have in the form (select tags could be more than one and it changes every time). Now, in order to see if any has been selected I loop through each element (selected option), and retrieve the "value" attribute. The default "option" tag has a value="0", so if any selected option returns a value greater than 0, I know at least one option has been selected, however it does not have to be in order, this is my loop so far:

for(var i = 0; i < totalSelected; i++){
  var eachOption = $(allSelected[i]).val();
  var defaultValue = 0;
  if(eachOption == defaultValue){
    ...redirect to another page
  }else if(eachOption > defaultValue){
    ... I display an alert
  }
}

My problem here is that as soon as the "if" matches a 0 value, it sends the user to the next page without testing the rest of the elements in the array, and the user could have selected the second or third options.

What I really want to do is check all the elements in the array and then take the next action, in my mind this is how I could do it, but I'm not getting it right:

var randomValue = 25;  
for(randomValue in allSelected){
  var found = true;
  var notFound = false
  if(found){
    display an alert
  }else{
    redirect to next page
  }
}

This loop or the logic I'm using are flawed (I'm pretty sure), what I want to do is test all the elements in the array against a single variable and take the next action accordingly.

I hope this makes some sense to you guys, any help would be appreciated.
Thanks,
JC

© Stack Overflow or respective owner

Related posts about JavaScript