On selection from drop-down A (HTML select
) I need to populate another "sub"-dropdown with a different list of values. For instance, on selection of country in dropdown A, dropdown B should be filled with the list of cities of selected country.
This is my first attempt of writing such a thing in jQuery. Please point out areas for improvement, like more idiomatic or shorter way of achieving this result (without losing much readability if possible).
HTML:
<select id="Parentlist">
</select>
<select id="Sublist">
</select>
<table id="choices">
<tr id="Poland" style="display:none">
<td id="Krakow"></td>
<td id="Warszawa"></td>
</tr>
<tr id="Germany" style="display:none">
<td id="Frankfurt"></td>
<td id="Berlin"></td>
</tr>
</table>
JavaScript + jQuery:
function populateParentlist(choice) {
$('#choices').find('tr').each(function() {
trowid = $(this).attr('id');
$("#Parentlist").append('<option>' +trowid + '</option>');
});
}
function populateSublist(choice) {
$('#Sublist').find('option').remove();
$('#choices').find('tr').each(function() {
trowid = $(this).attr('id');
$(this).find('td').each(function() {
tdid = $(this).attr('id');
if(trowid != choice)
return;
$('#Sublist').append('<option>' + tdid + '</option>');
});
});
}
populateParentlist('Poland')
populateSublist('Poland')
$(function() {
$("#Parentlist").change(function() {
var parsel = $(this).val();
populateSublist(parsel);
});
});