1

How to convert this javascript code to jquery ?

var ddlArray= new Array();
var ddl = document.getElementById('ddl');
for (i = 0; i < ddl.options.length; i++) {
   ddlArray[i] = ddl .options[i].value;
}

I think one can convert ddl = document.getElementById('ddl'); to ddl = $('#ddl'); but what can be done to the loop ?

4
  • But why? The original code works in every browser since IE5, is future proof, not reliant on any library, is easily maintained by anyone with basic javascript knowledge and runs very much faster. The only part where jQuery would be useful is in getting the value of the options, but the accepted answer doesn't use it for that. Commented Oct 13, 2014 at 0:59
  • I didn't know jquery was so much slower, does it mean that one shouldn't use jquery ? Commented Oct 13, 2014 at 1:04
  • Not my decision, but you should be aware of all factors when making decisions. If you just want less code (which isn't a good reason on its own), a plain JS version is var ddlArray = [].map.call(document.getElementById('ddl').options, function(opt){return opt.value;});. Note that you'll need a polyfill for .map for IE8, there are libraries to give IE 8 ES5 features. Commented Oct 13, 2014 at 1:08
  • 1
    taste the future (or now in ff, ch): [].map.call(dd1.options, (a) => a.value) Commented Oct 13, 2014 at 1:11

1 Answer 1

5

Using .map() + .toArray():

var ddlArray = $('#ddl option').map(function() {
    return this.value;
}).toArray();

Or .toArray() + the generic iterator $.map():

var ddlArray = $.map($('#ddl option').toArray(), function(option) {
    return option.value;
});

Live demo

Sign up to request clarification or add additional context in comments.

11 Comments

Thank you, do you know where I could find the documentation to learn to do this kind of things ?
@Wicelo no problem, I've just added links to the jQuery API docs in the answer. =]
You don't even need to call $.makeArray, just $.map over the array-like jQuery collection.
@Bergi I'm aware of that, however the documentation for $.map frowns upon iterating array-like objects without first converting them to real arrays: "Array-like objects — those with a .length property and a value on the .length - 1 index — must be converted to actual arrays before being passed to $.map(). The jQuery library provides $.makeArray() for such conversions."
@Bergi in my actual code, I have never used $.makeArray() for this use case either, but it is good to keep answers inline with the docs for future-proofness I believe. Anyway, I've switched $.makeArray() by .toArray() to make that sample less ugly.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.