Show / hide options from the drop-down list based on the selection of another drop-down list, then restore the initial state

advertisements

I have these two drop downs:

HTML

<select id="theYear">
    <option value="0">Select Year</option>
    <option value="2014">2014</option>
    <option value="2013">2013</option>
    <option value="2012">2012</option>
    <option value="2011">2011</option>
</select>
<select id="theFolders">
    <option value="0">Select Folder</option>
    <option value="2013 Blah Blah">2013 Blah Blah</option>
    <option value="2012 Blah Blah">2012 Blah Blah</option>
    <option value="2010 Blah Blah">2010 Blah Blah</option>
    <option value="2014 Blah Blah">2014 Blah Blah</option>
    <option value="2011 Blah Blah">2011 Blah Blah</option>
</select>

I was able to show / hide selecting options from the #theYear drop down without any issues. But I need to once I go back to the #theYear again, to rearrange the theFolders dropdown to its default state, which means the "Select Folder" selected.

JQuery:

 $('#theYear').on('change', function () {
     FY = $(this).find('option:selected').text();
     $('#theFolders').each(function () {
         $('option:not(:contains(' + FY + '))', this).hide();
     });
 });

 $('#theYear').on('mousedown', function () {
     $('#theFolders option').show()
      .find('option:contains("Select")', this)
      .attr('selected', 'selected');
});

My Fiddle

Thanks!


You just need to check the value of your FY variable (and previously set it to your option val, not text):

$('#theYear').on('change', function () {
     FY = $(this).find('option:selected').val();
     console.log(FY);
     if(FY != "0") {
         $('#theFolders').each(function () {
             $('option:not(:contains(' + FY + '))', this).hide();
         });
     } else {
         $('#theFolders option').show();
     }
 });

 $('#theYear').on('mousedown', function () {
     $('#theFolders option').show().find('option:contains("Select")', this).attr('selected', 'selected');
 });

The values also needed to be corrected in the first select (in your initial version, the value attribute is always equal to 2014.

See updated fiddle: http://jsfiddle.net/x00te027/1/