根据下拉选择显示特定内容?

时间:2018-02-25 21:10:52

标签: jquery html drop-down-menu

我正在尝试将此代码调整为我正在进行的项目。我发现它在这里提到了。

https://jsfiddle.net/zsL98g01/15/

我需要根据下拉选项的选择填充下面的文字。 因此,如果选择House Ware + Camera =它会显示摄像机列表。此列表仅在上述2个选项中找到。我需要每个组合能够提供基于文本的列表。

HTML:

    <select name="category1" id="category1">
                    <option value="">Select Category1</option>
                    <option value="home_ware">Home Ware</option>
                    <option value="education">Education</option>
                    <option value="books">Books</option>
                </select>

    <select disabled="disabled" class="subcat" id="category2" name="category2">
                    <option value>Select Category2</option>
                    <!-- Home Ware -->
                    <option rel="home_ware" value="air-conditioners_coolers">Air-Conditioners/Coolers</option>
                    <option rel="home_ware" value="audio-video">Audio/Video</option>
                    <option rel="home_ware" value="beddings">Beddings</option>
                    <option rel="home_ware" value="camera">Camera</option>
                    <option rel="home_ware" value="cell-phones">Cell Phones</option>
                    <!-- Education -->
                    <option rel="Education" value="Colleges">Colleges</option>
                    <option rel="Education" value="Institutes">Institutes</option>
                    <option rel="Education" value="Schools">Schools</option>
                    <option rel="Education" value="Tuitions">Tuitions</option>
                    <option rel="Education" value="Universities">Universities</option>
                    <!-- Books -->
                    <option rel="Books" value="College Books">College Books</option>
                    <option rel="Books" value="Engineering">Engineering</option>
                    <option rel="Books" value="Magazines">Magazines</option>
                    <option rel="Books" value="Medicine">Medicine</option>
                    <option rel="Books" value="References">References</option>
                </select>

JS + jQuery:

    $(function(){

var $cat = $("#category1"),
    $subcat = $("#category2");

$cat.on("change",function(){
    var _rel = $(this).val();
    $subcat.find("option").attr("style","");
    $subcat.val("");
    if(!_rel) return $subcat.prop("disabled",true);
    $subcat.find("[rel="+_rel+"]").show();
    $subcat.prop("disabled",false);
});

});

CSS:

    #category2 option{
    display:none;
    }

    #category2 option.label{
    display:block;
    }

1 个答案:

答案 0 :(得分:0)

你可以这样做。

$subcat.on("change",function(){
    var elemToshow = $cat.val() + '-' + $subcat.val();

  switch(elemToshow) {
    case 'home_ware-camera':
        //Do something
      break;
      case 'education-Colleges':
      //Do something
      break;
      // ...    
  }

老实说,我认为你不需要在你的DOM中插入rel属性。