Scott Scott - 6 months ago 82
jQuery Question

jQuery hide dropdown box if select option contains one entry

I'm trying to hide a dropdown box if the select option contains only one entry. (like below) I only want to hide the first drop downbox in this case whilst the second box should remain visible.

<div class="dropdown-filter-div">
<select>
<option value="">Gifts/Offers</option>
</select>
</div>

<div class="dropdown-filter-div">
<select>
<option value="">Gifts/Offers</option>
<option value="Gift">Gift</option>
<option value="Gift">Gift</option>
<option value="Gift">Gift</option>
</select>
</div>


I don't know how to start it though, here's what I want to do.. (I also have two of these in different tabs on the page in question.

if ($(".dropdown-filter-div > select > option")) contains 1 option {
$(".dropdown-filter-div > select).hide();
});


EDIT

http://mobilereactor.co.uk/shop/mobile-phones/apple-iphone-6s-plus-128gb-rose-gold-deals/ mobile version (need a user agent switcher) with a popular mobile user agent to view problem.

Currently using @Kim Gysen

jQuery(document).ready(function($) {
var $el = $('.dropdown-filter > select > option');
console.log($el.length);
if($el.length == 1){
$el.parent().hide();
}
});


at the end of jq-assets.js but its not working. @Kim Gysen

Answer

If I understand you correctly, you are looking to remove the entire select list from the div if that select list has 1 or less options. So this is what I did to get it to work:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> 
    <script src="index.js"></script>
</head>
<body>
    <div class="dropdown-filter-div">
        <select>
            <option value="">2</option>
            <option value="">Gifts/Offers</option>
        </select>
    </div>

    <div class="dropdown-filter-div">
        <select>
            <option value="">1</option>
        </select>
    </div>

    <div class="dropdown-filter-div">
        <select>
            <option value="">3</option>
            <option value="">Gifts/Offers</option>
            <option value="">Gifts/Offers</option>
        </select>
    </div>
</body>

$(document).ready(function () {
    var allSelects = $('.dropdown-filter-div > select');

    allSelects.each(function(){
        if(this.length <= 1){
            $(this).hide();
        }
    });
});

I probably took your answer too far, but this will select only those select lists that were smaller than or equal to 1 option and hide them.