SaberTooth SaberTooth - 6 months ago 8
Javascript Question

open the hidden div if the relevant item is selected in the select box

I am using the following code to make a show hide based on the selection of the item in a select box,

The code is working fine where one issue is when the item is already selected, it does not open the div, i have to delect it and again select it to open the div.

here is the html and JS Code for this

<select name="licenseType" id="licenseType" class="licenseType" multiple>

<option value="1"
SELECTED>Truck License</option>

<option value="2"
>Car License</option>

<option value="3"
SELECTED>Two Wheeler</option>

<option value="4"
SELECTED>Four Wheeler</option>

<option value="5"
>Six Wheeler</option>

<option value="6"
SELECTED>Eight Wheeler</option>

<option value="7"
class="special" SELECTED>Special License</option>

<option value="8"
class="machine" >Machine Operator License</option>

</select>


JS Code:

$(".specialLicense").hide('5000');
$('select#licenseType').change(function () {
if ($('option:selected', this).hasClass('special')) {
$(".specialLicense").show('5000');
} else {
$(".specialLicense").hide('5000');
}
});

Answer

To fix it, you have to trigger the change event manually once,

 $('select#licenseType').change(function () {
    if ($('option:selected', this).hasClass('special')) {
        $(".specialLicense").show('5000');
    } else {
        $(".specialLicense").hide('5000');
    }
  }).change();

DEMO

Comments