根据从另一个下拉列表中的选择显示/隐藏下拉列表中的选项,然后重置为初始状态

时间:2014-09-16 14:10:15

标签: jquery html drop-down-menu

我有这两个下降:

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>

我能够显示/隐藏#theYear下拉菜单中没有任何问题的选项。但我需要再次回到#theYear,将theFolders下拉列表重新排列为默认状态,这意味着&#34;选择文件夹&#34;地选择。

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

谢谢!

2 个答案:

答案 0 :(得分:1)

你只需要检查你的FY变量的值(之前将它设置为你的选项val,而不是文本):

$('#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');
 });

还需要在第一个选择中更正这些值(在初始版本中,value属性始终等于2014

请参阅更新的小提琴:http://jsfiddle.net/x00te027/1/

答案 1 :(得分:1)

由于您的选择选项始终是您的第一个选项,我会使用eq()功能来选择它。

我还会将您的mousedown更改为focus(如果选择的重点是点击标签或选中标签)。

最后,如果您使用的jQuery版本高于1.6,我会使用prop代替attr来设置所选属性(但这对您的案例来说是可选的)

 $('#theYear').on('focus', function () {
     $('#theFolders option').show().eq(0).prop('selected', true);
 });

Example