child.attr('selectedIndex', 1);
Doesn’t seem to work in my case.
I have two cascading dropdown lists, a parent and a child. To start, they both contain the same values. When a user selects an item from the parent select box, it is removed as a choice in the child select.
Sometimes, the parent select box has only 3 items, the default and 2 values. When a user selects a parent value in this case, the only possible choice in the child select is the one remaining non-default value.
So, when the parent has only two values, I’d like to automatically select the non-default value that is left in the child box when a user selects something parent select.
The HTML I start with might be as follows:
<select name="from" class="from">
<option value="" selected="selected" class="default">Select a value</option>
<option value="na">One</option>
<option value="ja">Two</option>
</select>
<select name="to" class="to">
<option value="" selected="selected" class="default">Select a value</option>
<option value="na">One</option>
<option value="ja">Two</option>
</select>
Then if the user selects “One” in the parent, the child select should automatically have “Two” selected.
Here is my jQuery I use to remove a value from the child when a value in the parent is selected:
(function ($) {
function cascadeSelect(parent, child) {
var childOptions = child.find('option:not(.default)');
child.data('options', childOptions);
parent.change(function () {
childOptions.remove();
child.append(child.data('options').filter('.' + this.value))
.change();
if (child.data('options').length == 2) {
[select the last option here]
}
})
if (parent.val()) {
childOptions.not('.default, .' + parent.val()).remove();
}
}
$(function () {
cascadeForm = $('.askform');
pulldown_from = cascadeForm.find('.from');
pulldown_to = cascadeForm.find('.to');
cascadeSelect(pulldown_from, pulldown_to);
});
I’ve added the line that checks if there are only two options in the child select:
if (child.data('options').length == 2) {
[select the non-default child option here]
}
But I can’t figure out how to select the non-default child option. I thought I could do it by using the .selectedIndex:
child.attr('selectedIndex', 1);
But this seems to reference the original index values (the indexes as they were before I have removed the value selected in the parent).
So how can I automatically select the only non-default option in the child select when there are only two options to start with in the parent?
I think I found a few issues.
In this line:
It look like you’re trying to filter using a selector for the class (not the value). You should hopefully be able to fix this by changing your selector so it filters based on the value of the option:
The easiest way to select a value in a dropdown is to just use
val(). In other words, the line you’re after should read:I created a JS Fiddle if you want to see the whole thing working: http://jsfiddle.net/KkNHr/1/