0

I want to run one single .append() after my .each() for efficiency. I tried to build out my set of objects and it won't run. It's similar to this question, except I'm building a jQuery object instead of a string.

JQuery append to select with an array

HTML

<select></select>

jQuery

var items = ['apple','pear','taco','orange'],
    options = '';

jQuery.each(items, function(i, fruit){
    options += jQuery('<option/>', {
        value: fruit,
        text: fruit
    });
}); //added missing ');'

jQuery('select').append(options);

2 Answers 2

1

Does it need to be an object? Why not just append to a string, then append that string afterwards?

$.each(items, function(i,fruit){
    options += "<option value='"+fruit+"'>"+fruit+"</option>";
});
Sign up to request clarification or add additional context in comments.

Comments

0

You should not concatenate objects, your code results in [object Object][object Object]... Also you are missing ) for closing each method.

$.each(items, function (i, fruit) {
    options += '<option value=' + fruit + '>' + fruit + '</option>';
});

$('select').append(options);

http://jsfiddle.net/NxB6Z/

Update:

var items = ['apple', 'pear', 'taco', 'orange'],
    options = [];

jQuery.each(items, function (i, fruit) {
    options.push($('<option/>', {
        value: fruit,
        text: fruit
    }));
});

jQuery('select').append(options);

http://jsfiddle.net/HyzWG/

5 Comments

So, there's no way to do it with an object?
You can't append an array. So this solution doesn't work. I'll go with the string approach, unless you know of a way to make an array work without a loop.
@PatrickRobertSheaO'Connor "You can't append an array", that's not true, it works in the fiddle.
When I try, i get NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild] as the error. When I console.log(options) I see that it's a group of options. Not sure what else could be the difference.
Okay, I discovered why this isn't working. I'm on jQuery 1.7.2 and this code doesn't work in that version.

Your Answer

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