Search code examples
jqueryhidedropdown

How can I hide all options in a dropdown list except the max value?


I've built a content submission form for an online magazine that has a dropdown list pre-populated with a list of incremental values, corresponding with the "issues" of the magazine (Issue 1, Issue 2, etc.), and where the option values of each choice auto increment.

<select name="input_7" id="input_23_7" class="large gfield_select" tabindex="2" aria-required="true" aria-invalid="false">
<option value="">-- select a Issue --</option>
<option value="351">Issue 1</option>
<option value="370">Issue 2</option>
</select>

In the above example, I would want to hide/remove everything before Issue 2. Going forward, the ideal solution would hide everything before whatever is the current/latest issue - somehow only displaying the max value within that dropdown, so that users have only one option to choose (the latest issue) when submitting content.

Because it's been pre-populated from an existing list of values, it can't be manually overridden, so I'm looking for a way, via JQuery preferably, to only show the latest option available.

As a temporary workaround, while the magazine is young and so has few options available anyway, I've taken the text from each option via jQuery and added it as a class to the respective option, enabling me to target it either via CSS to hide it, or via jQuery's remove() function, as below.

(function($){
    $('#input_23_7 option').each(function(){
        var theText = $(this).html();
        var cleanText = theText.replace(/ /g, "_");
        $(this).addClass(cleanText);
    });

    $('#input_23_7 option.Issue_1').remove();

})(jQuery);

This works fine in the short-term, but I would need to manually add each issue to be removed each time, and as this gets incrementally larger and larger, this becomes an impractical solution longer-term.

I'm sure there is a more eloquent solution, but it's beyond the scope of my limited expertise. Any help would be appreciated.


Solution

  • I think something like this should solve your issue.

    $('#input_23_7').find('option').not(':last').remove();    
    

    This should remove everything but the last option.