简体   繁体   English

根据表单输入显示/隐藏选项

[英]Show/hide option based on form input

I have two selectmenu's.我有两个选择菜单。 One named #c1 and one named #c2.一个名为#c1,一个名为#c2。 #c2 is hidden and will be shown when an option (any option) in c1 is selected. #C2被隐藏,并且在选择C1中的选项(任何选项)时将显示。 This works fine, however i would like a small adjustment that i can't seem to figure out due to my limited knowledge of Javascript/jQuery.这很好用,但是我想要一个小的调整,由于我对 Javascript/jQuery 的了解有限,我似乎无法弄清楚。

When #c1's option "meta" is selected, i would like to show #c2 as with any other option, but i would like #c2 to have an aditional option. When #c1's option "meta" is selected, i would like to show #c2 as with any other option, but i would like #c2 to have an aditional option.

Eg例如

<select id="c1">
<option>Option 1</option>
<option>Option 2, etc.</option>
<option>Metadata</option>
</select>

<select id="c2">
<option>Option 1</option>
<option>Option 2, etc.</option>
<option>Metadata</option> // This should be shown only when "metadata" in #c1 is selected and hidden when not.
</select>

A problem i came accross is that options are hard to hide using just CSS and my JS-knowledge is limited.我遇到的一个问题是,仅使用 CSS 很难隐藏选项,而且我的 JS 知识有限。 A solution is here , but i can't mold that into the chained selection that i want. 这里有一个解决方案,但我无法将它融入我想要的链式选择中。

I created a Fiddle here, so you can see all selectboxes and the current JS.我在这里创建了一个Fiddle ,所以你可以看到所有的选择框和当前的 JS。

I'm not sure it's the best way to do it but i guess it will work:我不确定这是最好的方法,但我想它会起作用:

var optionsArray = [{'key':'1','value':'val1','text':'Option 1'},
           {'key':'2','value':'val2','text':'Option 2, etc.'},
           ]; // Array of the #2 Options without the metadata


$('select[name="c1"]').change( function() {

    // Put your show/hide code here

    $('select[name="c2"] option').remove();// remove all the c2 options (In case there is already metadata)
    $.each(optionsArray, function(i){ //add all the basic options
          $('select[name="c2"]').append($("<option></option>")
            .attr("value",optionsArray[i]['value'])
              .text(optionsArray[i]['text']));
    });

    var valSelect1 = $(this).val();
    if (valSelect1 == 'Metadata'){ // add metadata only if the c1 option is metadata
         $('select[name="c2"]').append('<option value="Metadata">Metadata</option>');
    }
});

Hope It'll help希望它会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM