简体   繁体   中英

Populating a select element with comma-separated values using for loop

I have a bunch of comma-separated values stored as strings in a JSON file. My aim is to split these values to populate a select element which is based on Selectize.js. Code (excerpt) looks as follows:

var options = {};

var attr_split = data.attributes['Attribute1'].split(",");

var options_key;

for (var i = 0; i < attr_split.length; i++) { 
    options_key = attr_split[i]
    }

var options_values = {
    value: options_key,
    text: options_key,
    }

    if (options_key in options)
        options_values = options[options_key];
    options[options_key] = options_values;

$('#input').selectize({
    options: options,
});

Although this seems to work, the output in the select element only shows the last iterations done by the for loop. As per here and here , I've tried

for (var i = 0; i < attr_split.length; i++) { 
    var options_key += attr_split[i]
    }

but this throws me undefined plus all concatenated strings without the separator as per the following example:

undefinedAttr1Attr2Attr3

When I simply test the loop using manual input of the array elements everything appears fine:

for (var i = 0; i < attr_split.length; i++) { 
    var options_key = attr_split[0] || attr_split[1] || attr_split[2]
    }

But this is not the way to go, since the number of elements differs per string.

Any idea on what I'm doing wrong here? I have the feeling it's something quite straightforward :)

when you declare 'options_key' ,you are not initializing it.so its value is undefined .when you concatenate options_key += attr_split[i] .in first iteration options_key holds undefined .so only you are getting undefinedAttr1Attr2Attr3 .

so declare and initialize options_key like.

var options_key="";

and in your loop

for (var i = 0; i < attr_split.length; i++) 
{ 
     options_key = attr_split[i]
}

Everytime you replace options_key with value of attr_split[i] .so after the loop it will contain last element value.corrected code is

for (var i = 0; i < attr_split.length; i++) 
{ 
    options_key += attr_split[i]
}

Just change var options_key; to var options_key="";

The reason you are getting undefined is because you have not defined the variable properly.

Here is a working example

 var attr_split = "1,2,3,4".split(",");

var options_key="";

for (var i = 0; i < attr_split.length; i++) { 
    options_key += attr_split[i]
    }

    alert(options_key);
var options_values = {
    value: options_key,
    text: options_key
}
alert(options_values);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM