Yelotofu

Yelotofu ~ “In building standards compliant sites we are creating a better Web for the future.”

Tip: getting values from an options list

Tags: , , , ,

So, if you've ever converted an options list into a single array of values you might have intuitively done this:

var select = $('#mySelectElement')[0];
var values = new Array();
for (var i=0; i < select.length; i++) {
  values.push(select.options[i].value);
}

Pretty boring aye?

There is a snazzier (is that a word?) alternative, which is to use jQuery.map:

var select = $('#mySelectElement')[0];
var values = $.map(select.options, function(n) {
    return n.value;
});

OK, only one line saving but doesn't that feel good?!?

Similar Posts

2 Comments

  1. By dalin at

    If this was PHP I would say “bad idea”. But I know much less about JavaScript so perhaps it’s not.

    in option 1 you use language constructs (I would think it would be even better to use values[] rather than the method .push). In option 2 you use a method to run a callback function on each element. I’m guessing there’s an order of magnitude difference in performance (if not more). Albeit with a select box there’s probably not too many options to iterate through, but other scenarios may have significantly more.

  2. By caphun at

    @dalin: Yes, definitely. Using values[] would be quicker than push but in most cases you won’t notice. If I were wearing my optimization hat I’d also use document.getElementById('mySelectElement') to add to that.

    jQuery.map at its heart is a for loop with a callback. That’s all it is. I see option one as a common pattern we run into often and option 2 as a possible solution to that pattern.

Leave a Reply

* marks a required field.



(this will not be published)