mm1975 mm1975 - 1 year ago 111
Javascript Question

jQuery each-Method append items twice

I want to fill a select dynamically with options (coming from a textarea, line by line). But the following snippet appends the items twice. Where I have the flaw? Thank you for your tips.

function changeOptions() {
var lines = [];
var lines = $('textarea').val().split('\n');
console.log ('lines.length ', lines.length);
for (var i = 0; i < lines.length; i++) {
$.each(lines, function(i, lines) {
$('#simulation').append($('<option>', {
value : lines,
text : lines

Answer Source

Why for AND each? You did it twice! :)

Here is a bit shorter version of your code. I like for more than each, because it is faster in loops like this. And for things like you want to do, for is perfectly easy to use.

function changeOptions() {
    var select = $('#simulation').empty(),
        lines = $('textarea').val().split('\n');

    for( var i = 0; i < lines.length; i++ )
        select.append($('<option>', {
            value : lines[i],
            text : lines[i]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download