I have a drop-down menu:
<select id="mySelect">
<option> select
<option value="fruits"> fruits
<option value="flowers"> flowers
</select>
When I select one of the options I need to build an un-ordered list from an array that I have:
var myFruits = ["apple","orange","banana"];
var myFlowers= ["rose","tulip","carnation"];
... and have the option become a header of the list, something like:
<ul>fruits
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
I also need to allow to have multiple select, i.e. User can select both options from the drop-down. I'm trying to use jQuery but have not gone too far:
$("#mySelect").click(function() {
if($(this).val() == "fruits") {
$("#myResults").append("<ul>"+$(this).val()+"</ul>");
}
});
Try this(I have used change event, you can easily change it to use click event if you think you need to handle click function for sure):
$("#mySelect").change(function() {
if($(this).val() == "fruits") {
var fruitsListHTML = "";
if($("#myResults").data("fruits") != "1"){
$.each(myFruits, function(a, b){
fruitsListHTML += "<li>" + b + "</li>";
});
$("#myResults").append("<ul>"+ fruitsListHTML +"</ul>");
$("#myResults").data("fruits", "1");
}
}
});
For a more generic solution:
<select id="mySelect" multiple>
<option> select </option>
<option value="fruits"> fruits
<option value="flowers"> flowers
</select>
<div id="myResults"></div>
<input type="text"/>
<script type="text/javascript">
var optionsList = {
fruits: ["apple","orange","banana"],
flowers: ["rose","tulip","carnation"]
};
$(function() {
$("#mySelect").change(function() {
var options = $(this).val();
$.each(options, function(i,e){
if($("#myResults").data(e) != "1"){
var listHTML = "";
$.each(optionsList[e], function(a, b){
listHTML += "<li>" + b + "</li>";
});
$("#myResults").append("<ul>"+ listHTML +"</ul>");
$("#myResults").data(e, "1");
}
});
});
});
</script>
You might be able to use a jQuery template to help out with this as well. For example, this would render the items in the list for you.
Edit I modified this to also use an attribute on the selected option to identify which data source to use.
var myFruits = [
{ Name: 'apple' },
{ Name: 'orange' },
{ Name: 'banana' }
];
var myFlowers = [
{ Name: 'rose' },
{ Name: 'tulip' },
{ Name: 'carnation' }
];
$(function () {
$('#mySelect').change(function () {
var option = $('#mySelect option:selected');
var data = eval((option).attr('data-source'));
$.tmpl('<li>${Name}</li>', data).appendTo('#tmpl-cont');
});
});
<select id="mySelect">
<option> select
<option data-source="myFruits" value="fruits"> fruits
<option data-source="myFlowers" value="flowers"> flowers
</select>
<ul id="tmpl-cont" />
Here's some more information on templates.
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