Javascript Question

Javascript optgroup hidden dont working IExlorer

This code is working in Opera, the problem is IE and Android.
Use

hiden()
javascript. First Option use value Mazda (mark) second shows us 'opera': only all models MAZDA (is good). 'IE': Shows us all model and all optgroup. Maybe is in JS problem?

$(document).ready(function() {
$('#model optgroup').hide();enter code here
$('#Marka').change(function() {
var text = $(this).val();
$('#model optgroup').hide();
$('#model').val('');
$('#model optgroup[label="' + text + '"]').css({
'display': 'block'
});


});
});

function usun() {
document.getElementById("first").style.display = "none";

}


https://jsfiddle.net/p051m5u6/

Answer

There are some errors in your HTML (jsfiddle): please pay attention to use different values for different IDs. Cannot exist two or more elements with the same ID.

The solution I propose you is to save and remove the optgroups on document ready and after to append the right one according to the selection:

var optGroup = {};
$(function () {
  // remove from second list all optgroup and save them in a global variable
  $('#model optgroup').each(function(index, element) {
    optGroup[element.label] = {'optGroup': element};
    $('#model optgroup:eq(0)').remove();
  });

  $('#Marka').change(function(){
    // remove the attached optgroup
    $('#model optgroup').remove();
    // search for the saved optgroup and attach it to the select
    $(optGroup[this.value].optGroup).appendTo('#model');
    $('#model optgroup option:selected').removeAttr("selected");
    $('#first2').prop('selected', true);
  });
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<select id="Marka" name="marka_auta">
    <option id="first1" >Marka:</option>
    <optgroup label="Marka Auta:">
        <option value="audi" >Audi</option>
        <option value="mazda" >Mazda</option>
    </optgroup>
</select>
<select id="model" name="model_auta">
    <option id="first2" disabled selected>Model:</option>
    <optgroup id="models1" label="mazda">
        <option>RX-8</option>
        <option>323F</option>
        <option>6</option>
    </optgroup>

    <optgroup id="models2" label="audi">
        <option>A6</option>
        <option>R8</option>
        <option>A4</option>
    </optgroup>
</select>

Comments