How can add the array data below into a select
box using JavaScript or jQuery?
var SHIFT_Plants = [
{ Plant: 0, PlantName: "" },
{ Plant: 2737, PlantName: "PM1" },
{ Plant: 2738, PlantName: "PM2" },
{ Plant: 2739, PlantName: "SSP" },
{ Plant: 2740, PlantName: "UT1" },
{ Plant: 2741, PlantName: "UT2" },
{ Plant: 2742, PlantName: "TW1" },
{ Plant: 2743, PlantName: "TW2" },
{ Plant: 2744, PlantName: "TW3" },
{ Plant: 2745, PlantName: "TW4" },
{ Plant: 2746, PlantName: "FL1" },
{ Plant: 2747, PlantName: "FL2" },
{ Plant: 2748, PlantName: "FL3" },
{ Plant: 2749, PlantName: "FL4" },
{ Plant: 2750, PlantName: "MS1" },
{ Plant: 2751, PlantName: "MS2" },
{ Plant: 2752, PlantName: "PY1" },
{ Plant: 2753, PlantName: "PY2" },
{ Plant: 2754, PlantName: "DDX" },
{ Plant: 2755, PlantName: "DT1" },
{ Plant: 2756, PlantName: "DT2" }
];
This is slightly faster and cleaner.
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
Adding multiple options
var newOptions = {
'red' : 'Red',
'blue' : 'Blue',
'green' : 'Green',
'yellow' : 'Yellow'
};
var selectedOption = 'green';
var select = $('#example');
if(select.prop) {
var options = select.prop('options');
}
else {
var options = select.attr('options');
}
$('option', select).remove();
$.each(newOptions, function(val, text) {
options[options.length] = new Option(text, val);
});
select.val(selectedOption);
Use jQuery as it supports a lot of functions.
Loop through the array with $.each and get each array item as Object. Then access the Object with its keys eg Plant
and PlantName
to get its values.
Remember to import jQuery into HTML file.
$(function(){ var SHIFT_Plants = [ { Plant: 0, PlantName: "test" }, { Plant: 2737, PlantName: "PM1" }, { Plant: 2738, PlantName: "PM2" }, { Plant: 2739, PlantName: "SSP" }, { Plant: 2740, PlantName: "UT1" }, { Plant: 2741, PlantName: "UT2" }, { Plant: 2742, PlantName: "TW1" }, { Plant: 2743, PlantName: "TW2" }, { Plant: 2744, PlantName: "TW3" }, { Plant: 2745, PlantName: "TW4" }, { Plant: 2746, PlantName: "FL1" }, { Plant: 2747, PlantName: "FL2" }, { Plant: 2748, PlantName: "FL3" }, { Plant: 2749, PlantName: "FL4" }, { Plant: 2750, PlantName: "MS1" }, { Plant: 2751, PlantName: "MS2" }, { Plant: 2752, PlantName: "PY1" }, { Plant: 2753, PlantName: "PY2" }, { Plant: 2754, PlantName: "DDX" }, { Plant: 2755, PlantName: "DT1" }, { Plant: 2756, PlantName: "DT2" } ]; $.each(SHIFT_Plants, function( key, value ) { var opt = "<option value="+ value.Plant +" >"+ value.PlantName +"</option>"; $('#test').append(opt); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="test"> </select>
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.