dedi wibisono dedi wibisono - 12 days ago 5
jQuery Question

Grouping option value by jQuery

How to I grouping

option value
.
here is my HTML

<select id="kota"> </select>


and my JS

var $sel = $('select#kota');
availableTags.forEach(function(tag) {
$sel.append('<optgroup label="'+tag.area+'"><option value="'+tag.stationcode +'">'+ tag.label +'</option></optgroup>');
});


I want to separate 'label' for Jakarta and Bandung. Any body help? or suggestion?
Here is my full code in jsfiddle. https://jsfiddle.net/dedi_wibisono17/u1be7gkq/7/

I want expected like this
enter image description here

Thank you

Answer

How about this solution. Hope it helps :)!

$(document).ready(function(){
       
var availableTags = [{
    label: "Bandung - Bandung (BD)",
    area: "Bandung",
    station: "Bandung",
    stationcode: "BD"
}, {
    label: "Bandung - Cicalengka (CCL)",
    area: "Bandung",
    station: "Cicalengka",
    stationcode: "CCL"
}, {
    label: "Bandung - Cikadongdong (CD)",
    area: "Bandung",
    station: "Cikadongdong",
    stationcode: "CD"
}, {
    label: "Jakarta - Gambir (GMR)",
    area: "Jakarta",
    station: "Gambir",
    stationcode: "GMR"
}, {
    label: "Jakarta - Jakarta Kota (JAKK)",
    area: "Jakarta",
    station: "Jakarta Kota",
    stationcode: "JAKK"
}, {
    label: "Jakarta - Jatinegara (JNG)",
    area: "Jakarta",
    station: "Jatinegara",
    stationcode: "JNG"
}];

var bandungArray = [];
var jakartaArray = [];
var output1 = [];
var output2 = [];

for(var i = 0 ; i < availableTags.length; i++){
	if((availableTags[i].label).indexOf("Bandung") !== -1){
		bandungArray.push(availableTags[i]);
	}
	else{
		jakartaArray.push(availableTags[i]);
	}
}

bandungArray.forEach(function(tag) {
	output1.push('<option value="'+ tag.stationcode +'">'+ tag.label +'</option>');
});
jakartaArray.forEach(function(tag) {
	output2.push('<option value="'+ tag.stationcode +'">'+ tag.label +'</option>');
});

$('#kota').html("<optgroup label='Bandung'>"+output1.join('') + "<optgroup label='Jakarta'>"+output2.join(''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select id="kota">
</select>

Comments