Reputation: 177
I have this dynamic HTML
<select id='posto'>
<select>
<ul id="nazioni">
<li data-dal="Europa, Mediterraneo">Italia</li>
<li data-dal="Europa, Mediterraneo">Spania</li>
<li data-dal="Asia">Cina</li>
<li data-dal="Europa, Asia, Mediterraneo">Turchia</li>
<li data-dal="Africa, Mediterraneo">Egitto</li>
<li data-dal="Europa">Francia</li>
<li data-dal="Europa">Svezia</li>
</ul>
and I'm trying to fill in the select with tags with the 'data-dal' values which I'm trying to split into separate values by the comma and space. I'm a fresh jQuery and Javascript novice, but I've managed to piece together some sort of code from what I found here on stackOverflow and in the jQuery manual but wasn't able to piece together all the pieces into my desired code.
var items = {};
$('#nazioni li').each(function () {
items[$(this).data('dal').split(', ')] = true;
});
var result = new Array();
for (var i in items) {
result.push('<option>' + i + '</option>');
}
$('#posto').show().empty().append(result.join());
$('#posto').change(function () {
var selected = $(this).find('option:selected').text();
$('li[data-dal=' + selected + ']').show();
$('li[data-dal!=' + selected + ']').hide();
});
http://jsfiddle.net/urnPG/ I jsfiddled it. I'm unable to split the data-dal values into separate values. I'd appreciate any help or pointers in better ways to do this.
Upvotes: 0
Views: 2912
Reputation: 1468
I am not sure if I have understood your question right. But let me help you with what I can. First of all heres the JSFIDDLE Updated.
I could split the <li>
elements values into a unique values array and populate the <Select>
with these values.
$('#nazioni li').each(function () {
var arr = $(this).data('dal').split(", ");
items = items.concat(arr);
});
var sorted = unique(items);
This function gets the unique values of the list.
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
I then tried to show up all the <li>
elements corresponding to the drop down value that is selected.
Upvotes: 4