javascriptjqueryfirefoxoptgroup

jQuery - Can not select first option on last optgroup


I have small problem. I need select option from <select> A, which triggered action and select his first <option> in <select> B by value from selected <option> from A. Everything works fine, but I can't select ONLY last optgroup and his option.

Try to look at jsfiddle

This bug seems to be only on Firefox (Linux, Win7). Google Chrome is ok. Any ideas?

Code (html):

<select id="charset" name="charset">
    <option value=""></option>
    <option value="armscii8">ARMSCII-8 Armenian</option>
    <option value="ascii">US ASCII</option>
    <option selected="selected" value="utf8">UTF-8 Unicode</option>
</select>

<select id="collation" name="collation">
    <optgroup label="armscii8">
        <option value="armscii8_bin">armscii8_bin</option>
        <option value="armscii8_general_ci">armscii8_general_ci</option>
    </optgroup>
    <optgroup label="ascii">
        <option value="ascii_bin">ascii_bin</option>
        <option value="ascii_general_ci">ascii_general_ci</option>
    </optgroup>
    <optgroup label="utf8">
        <option value="utf8_bin" selected="selected">utf8_bin</option>
        <option value="utf8_czech_ci">utf8_czech_ci</option>
        <option value="utf8_danish_ci">utf8_danish_ci</option>
        <option value="utf8_esperanto_ci">utf8_esperanto_ci</option>
    </optgroup>
</select>`

Code js:

(function($){

function setCollation(charset) {
    $('#collation optgroup option').removeAttr('selected');
    $('#collation optgroup').hide(0);

    if (charset && charset != '') {
        $("#collation optgroup[label='" + charset + "']").show(0);
        $("#collation optgroup[label='" + charset + "'] option:first").attr('selected', 'selected');
    }
}

$('#charset').change(function() {
    setCollation($(this).val());
});
setCollation($('#charset').val());

})(jQuery);

I updated jsfiddle where I removed show/hide functions.

I will try to reproduce how script works:

  1. When I select Collation from first select box (fe. value DOS Russin), second select is selected as I need.

  2. I changed first select value to another one. In this moment is everything ok.

  3. ! I changed back to the DOS Russian and in this moment the second select box is not selected as in first step.

This is a very strange behavior and I can't to do works in FF.


Solution

  • Well I can't explain why the browser behavior is inconsistent but I can tell you that changing to .prop seemed to have solved the problem.

     $('#collation optgroup').prop('disabled', true);
        $('#collation option').removeAttr('selected');
    
        if (charset && charset != '') {
            $("#collation optgroup[label='" + charset + "']").prop('disabled',false);
            $("#collation optgroup[label='" + charset + "'] > option:eq(0)").prop('selected', true);
    

    See it in action:

    http://jsfiddle.net/8pAAp/1/