Question

I am using a simple little script that should allow a drop down list to enable/ disable the second dropdown list with the relevant data, but it is not working correctly.

Here is all the code and html:

$("[name='pet_type']").change(function () {
    var pet_type = $(this).val();
    $("[name='breed']").removeAttr("disabled");
    $("select[name='breed'] > option").each(function () {
        var o = $(this);
        console.log(o.data('pet-type'));
        console.log(pet_type);
        if (o.data('pet-type') === pet_type) {
            o.hide();
        } else {
            o.show();
        }
    });
});

HTML:

<select name="pet_type">
    <option></option>
    <option value="Cat" data-pet-type="Cat">Cat</option>
    <option value="Dog" data-pet-type="Dog">Dog</option>
</select>
<select name="breed" disabled="disabled">
    <option></option>
    <option data-pet-type="Cat" disabled="disabled">--- Cat Breeds</option>
    <option value="Chartreux" data-pet-type="Cat">Chartreux</option>
    <option value="Cymric" data-pet-type="Cat">Cymric</option>
    <option data-pet-type="Dog" disabled="disabled">--- Dog Breeds</option>
    <option value="Affenpinscher" data-pet-type="Dog">Affenpinscher</option>
    <option value="Anatolian Shepherd Dog" data-pet-type="Dog">Anatolian Shepherd Dog</option>
    <option value="Other">Other</option>
</select>

All that is happening is when you click on an option is the first downdrop, it just enables the second dropdown with all the data for cats and dogs, when really it should only enable data for the 1 option that is selected.

If anyone has any ideas on why this is not working correctly that would be much appreciated.

Was it helpful?

Solution

The problem is simply that you can't hide individual option tags in most browsers. Instead, you can disable them:

o.prop('disabled',true); // or false

or .detach() the unwanted options and re-attach them later:

window.all_options = $("[name='breed'] > option").detach(); // global variable

$("[name='pet_type']").change(function () {
    var pet_type = $(this).val();
    $("[name='breed']").removeAttr("disabled").append(window.all_options);
    $("select[name='breed'] > option").each(function () {
        var o = $(this);
        if (o.data('pet-type') !== pet_type) {
            o.detach();
        }
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top