I am new to jQuery and am having a problem selecting an item in a select list. I have implemented cascading select boxes as show in this post. Everything is working fine except for setting a default.
The problem is that I need to select one of the child items when the page is first loaded.
Code:
<script type="text/javascript">
function cascadeSelect(parent, child, childVal) {
var childOptions = child.find('option:not(.static)');
child.data('options', childOptions);
parent.change(function () {
childOptions.remove();
child
.append(child.data('options').filter('.sub_' + this.value))
.change();
})
childOptions.not('.static, .sub_' + parent.val()).remove();
if (childVal != '') {
child.find("option[value=" + childVal + "]").attr("selected", "selected");
}
}
$(function () {
cascadeForm = $('.cascadeTest');
parentSelect = cascadeForm.find('.parent');
childSelect = cascadeForm.find('.child');
cascadeSelect(parentSelect, childSelect, "5");
});
</script>
HTML:
<select class='parent' name='parent' size='10'>
<option value='1'>Category 1 -></option>
<option value='2'>Category 2 -></option>
</select>
<select class='child' id='child' size='10'>
<option class='sub_1' value='5'>Custom Subcategory 1.1</option>
<option class='sub_1' value='3'>Subcategory 1.1</option>
<option class='sub_2' value='4'>Subcategory 2.1</option>
</select>
The second select list should show up inside the right box but it does not.

The child.find call is being hit but does not select the item.
What am I doing wrong?
Edit:
The problem with your code is that you remove every single “child” option form the DOM!
In your html there are not childOptions with
staticas a class, so the above removes all existingchildOptions. This is why you see nothing on the right.Otherwise, it’s a little unclear what you’re trying to do with
.data()but the default selection works if you remove that line:jsFiddle example
.find()will look in the descendants, maybe you want to.filter()the selected elements?:Also, I often have better luck using
.attr("selected", true)andfalseto deselect.Here is a jsFiddle example that sets the default value of an options list.