I've got string with IDs and Names separated by ^ (between ID and Names) and ; (between sets) for example
var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";
I need to get something like this
$('#1').html('<option value="1">John Smith</option><option value="2">Sophia Williams</option><option value="3">Emily Johnson</option>');
I tried loops but got stuck:
var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";
var a = string.split(";"),
i;
for (i = 0; i < a.length; i++){
if (a[i] !== ""){
var b = a[i].split("^"),
i2;
for (var i2 = 0; i2 < b.length; i++) {
var name = b[i2];
console.log(name);
}
}
}
Im not sure that it's good way
Using Option()
new Option(text, value, defaultSelected, selected)
var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;"
var options = string.split(';').map(i => {
return new Option(...i.split('^').reverse())
})
$('#1').html(options)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="1"></select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With