Reputation: 9173
EXPLANATION
:
I have two element with as many options inside them.
the first contains a series of options which have their db-id as their values. these are parents.
the second element is populated with a list of options which have their parent db-ids as their values and their own db-ids as their html id-attribute. these are children categories.
PROBLEM: I want to have all the children cats to be hidden, and on each select event of any parent category, the relative children to become visible, using their values which is identical to their parent's value.
MY ATTEMPTS: For this purpose, I have written the following script which does not work. It attaches a click event to each parent category, and this event triggers a function which is responsible to turn the visibility of any child cat on, if their values matches the values of the clicked element.
HTML CODE:
<select multiple name="branch" >
<option selected="" value="false">Please Select a Branch</option>
<option class="branch-item" value="0">Computer</option>
<option class="branch-item" value="1">Automobile</option>
<option class="branch-item" value="4">Technical</option>
</select>
<select multiple class="form-option" name="subbranch" >
<option class="subbranch-item" style="display: none;" value="1">Software</option>
<option class="subbranch-item" style="display: none;" value="1">Hardware</option>
<option class="subbranch-item" style="display: none;" value="7">Mechanics</option>
<option class="subbranch-item" style="display: none;" value="7">Welding</option>
</select>
JQUERY CODE:
<script type="text/javascript">
$(document).ready(function(e) {
$(".branche-item").click(function(){
var values = $(this).val();
$('.subbranch-item').parent().each(function(element, value) {
if(value == values)
{
element.show();
}
});
});
});
</script>
I appreciate any help on the debugging of the jquery code, thanks
Upvotes: 1
Views: 599
Reputation: 17587
$('select[name="branch"]').change(function () {
var $branch = $(this).children(':selected'),
$subbranch = $('[name="subbranch"]').children('option');
$subbranch.hide()
$branch.each(function () {
var branch = $(this).val();
$subbranch.each(function () {
if ($(this).val() == branch) {
$(this).show();
}
});
});
}).change();
Upvotes: 1
Reputation: 388316
Try
var $sub = $('select[name="subbranch"]');
var sub = $.trim($sub.html());
$('select[name="branch"]').change(function () {
var filter = $(this).children('option:selected').map(function () {
return '[value="' + this.value + '"]'
}).get().join();
$sub.empty().append($(sub).filter(filter))
}).change()
Demo: Fiddle
Upvotes: 1