1

very simple but guess what, not for me. I have a comma separated list like this: Option1,Option2,Option3 that I want to append to a <select> so it becomes <select><option>Option1</option><option>Option2</option><option>Option3</option></select>

I can "split" the list like this (inside a function that gets the list):

var optionsarray = $(this).val().split(',');

    $(optionsarray).each(function(i){
        var seloption = '<option value="'+optionsarray[i]+'">'+optionsarray[i]+'</option>'; 
    });

But now how do I append seloption to my select list. If I put

$('#selecttoappendto').append('<option value="'+optionsarray[i]+'">'+optionsarray[i]+'</option>');

or

$('#selecttoappendto').append(seloption);

inside the each loop nothing happens. Take it outside the each I can append say optionsarray[0], or optionsarray[1] etc. but I cannot get to append optionsarray[i] which ever way I do it (inside or outside the each). Help please - thanks in advance

3 Answers 3

3

Starting with an empty string, you can build a string in the loop usingt +=. Then .append() the string.

var optionsarray = $(this).val().split(',');

var seloption = "";

$.each(optionsarray,function(i){
    seloption += '<option value="'+optionsarray[i]+'">'+optionsarray[i]+'</option>'; 
});

$('#selecttoappendto').append(seloption);

or another option would be to build the elements separately, store them in a container, then append them from the container.

var optionsarray = $(this).val().split(',');

var temp_sel = $('<select>');

$.each(optionsarray,function(i){
    temp_sel.append('<option>',{text:optionsarray[i],
                                value:optionsarray[i]
                                });
});

temp_sel.children().appendTo('#selecttoappendto');

Fixed missing () after children.

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

2 Comments

many thanks, perfect, I "know" about += - bit like .= in PHP but could not get it to work, assume that is why you declare var seloption = ""; first
@Russell: Yes exactly, you need to initialize it with an empty string before you +=.
1

Here's what I wrote and use; it's a little faster than the solution user113716 gave, because you're skipping creating the temp select, all those appends to that temp select (even if it is a DOM fragment, it still takes some time), and you're also skipping the .children() find and unwrapping at the end for that final append.

// Appends multiple elements all at once; maintains chaining
$.fn.appendAll = function ($eleArr) {
    var numEles = $eleArr.length
    ,    $useEle = new $();
    if (numEles) {
        while (numEles--) {
            $useEle = $eleArr[numEles].add($useEle);
        }
        return $(this).append($useEle);
    }
};

// Prepends multiple elements all at once; maintains chaining
$.fn.prependAll = function ($eleArr) {
    var numEles = $eleArr.length
    ,    $useEle = new $();
    if (numEles) {
        while (numEles--) {
            $useEle = $eleArr[numEles].add($useEle);
        }
        return $(this).prepend($useEle);
    }
};

So:

var optsArr = $(this).val().split(','),
    $options = [],
    thisOption;

$.each(optsArr, function(i) {
    thisOption = '<option value="' + optsArr[i] + '">' + optsArr[i] + '</option>';
    $options.push($(thisOption));
});

$yourSelect.appendAll(optsArr);

I actually wrote those plugins for exactly this; doing it this way, I build a 1500+ option select in under 250 ms. :D

2 Comments

In case anyone's wondering it should be $yourSelect.appendAll($options);
I'm guessing it was different in 2012 but these days the built-in .append can also take an array, so it behaves just like the .appendAll here and you don't need this any more (same deal with .prepend). +1 for making it work back in the day, though.
0

jQuery's .append can take an array these days (dunno what it was like in 2012), so this works too:

let vals = $(this).val().split(',');
$('#myselect').append(vals.map(v => $('<option/>').text(v).attr({value:v})));

The $.map function can also be used. It will create a jQuery array that has an .appendTo:

$.map($(this).val().split(','), v=>$('<option/>').text(v).attr({value:v}))
  .appendTo('#myselect');

Comments

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.