jquery get select options to array

时光总嘲笑我的痴心妄想 提交于 2019-12-10 15:57:39

问题


I'm kind of stuck with one - presumably simple to resolve problem.

I want to create the code which will be used for all select elements on the site.

Depending on the "label" attribute assigned to the "option" I want to hide all other "div" elements which have classes the same as other "label" values of the "options" in this specific "select" menu.

Let me demonstrate:

 <select class="sel_depend" id="reg_where_heard" name="where_heard">
    <option value="">Select one…</option>
    <option value="1">Google</option>
    <option value="2">Yahoo</option>
    <option value="3" label="where_heard_magazine">Magazine</option>
    <option value="4" label="where_heard_other">Other</option>
</select>

<div class="where_heard_magazine dn"><input type="text" name="magazine" id="magazine" value="" /></div>
<div class="where_heard_other dn"><input type="text" name="other" id="other" value="" /></div>

Now - "dn" class in the div under the menu has simply "display:none" assigned.

Depending on the selected option - if it's value is 3 - I want the div with the class the same as the label to show - then if I select option with value 4 - all other divs (where class names would be populated from all options of this select element) should hide() and only selected show().

I'm not quite sure how to put all "option" elements of the specific "select" element to array. Then presumably I could loop through it using each() statement and find out whether they have "label" and if so - hide the element with the class matching its value.

then after the loop I could show the element with the class which matches the value of the "label" parameter of the selected "option".

I hope that makes sense.

Any idea how to achieve this?

Many thanks.


回答1:


give all the divs related to a specific select a class that is the name of that element. then you can do something like:

$('.sel_depend').change(function(){
    var class = $(this).attr('name');
    $('.' + class).hide();
    var divToShowClass = $(this).find(':selected').attr('label');
    $('.' + divtoShowClass).show();

});



回答2:


  $('.sel_depend').change(function() {
    var optionWithLabels = $('.sel_depend').children("option[label]");
    if($("option:selected", this).attr('label')) {
        optionWithLabels.each(function(){
            $('.' + $(this).attr('label')).hide();
        });
        $('.' + $("option:selected", this).attr('label')).show();
    }
  });


来源:https://stackoverflow.com/questions/3365997/jquery-get-select-options-to-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!