jQuery filter select options

早过忘川 提交于 2019-12-09 03:22:59

问题


Is it possible to filter specific select options?

I have a code :

<select id="adcategory" name="adcategory">
    <option value="">Select</option>
    <option value="25" class="dropdownparentcategory">Florida Atlantic University</option>

    <option value="26">- Books </option>
    <option value="27">- Electronics</option>
    <option value="28">- For Rent</option>

    <option value="17" class="dropdownparentcategory">Florida International University</option>

    <option value="18">- Books</option>
    <option value="19">- Electronics</option>
    <option value="20">- For Rent</option>

    <option value="1" class="dropdownparentcategory">Florida Tech</option>
    <option value="2">- Books</option>
    <option value="3">- Electronics</option>
    <option value="7">- For Rent</option>


</select>

So if the variable for example $school = Florida Atlantic University than show only thoes options witch is till next school category ( .dropdownparentcategory ), so in this case they would be only :

<select id="adcategory" name="adcategory">
    <option value="">Select</option>

    <option value="26">- Books </option>
    <option value="27">- Electronics</option>
    <option value="28">- For Rent</option>

</select>

As you can see in this image :

Is it possible to create with jQuery?


回答1:


This looks like potentially bad design. I would suggest moving to <optgroup> [MDN] tags to group your drop down items:

<select>
    <optgroup label="Florida Atlantic University">
        <option value="1">Text</option>
        <option value="2">Text</option>
        <option value="3">Text</option>
    </optgroup>
    <optgroup label="Florida Tech">
        <option value="4">Text</option>
        <option value="5">Text</option>
        <option value="6">Text</option>
    </optgroup>
</select>

Then it's trivially easy to select child elements;

$('optgroup[label*="' + yourSchoolName + '"]').find('option')



回答2:


Sure is.

$("#adcategory option:contains('Florida International University')").nextUntil(".dropdownparentcategory")

http://jsfiddle.net/Xeon06/YEeMH/




回答3:


i would say, add classes for all your element by categorizing

<option class="js_atl" value="25" />
<option class="js_atl" value="26" />
<option class="js_atl" value="27" />
<option class="js_int" value="28" />
<option class="js_int" value="29" />

so like that you can use ur $school = "Florida Atlantic University" show or append or what ever with $(".js_atl") for the other category $(".js_int") which returns array of selected elements in that class category.

hope this helps.




回答4:


You should be able to apply a style of "display: none;" to the tags you don't want visible.



来源:https://stackoverflow.com/questions/7068331/jquery-filter-select-options

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