Dynamic select

There are many different ways to solve this particular issue. For example, all of the options could be removed from the HTML code with only the JavaScript generating what is needed.

However, even though this is the JavaScript forum we must never lose sight of the no-JavaScript situations. But, Everyone has JavaScript, right? No they bloody well do not, as is demonstrated nicely at that link. It’s important that we accommodate people without it as much as possible.

Another benefit of improving the HTML side of things, is that it often leads to better JavaScript solutions too.

Improve the HTML-only approach

Currently the options list is too cluttered for someone to easily make sense of it. Adding in some category options to help people more easily understand the groupings, is a good approach here.

    <select id="myDropdown">
        <option value="" disabled>100% Options</option>
        <option value="0" data-imagesrc="images/Alignment_0.png">None</option>
        <option value="" disabled>50% Options</option>
        <option value="1" data-imagesrc="images/Alignment_1.png">Left</option>
        <option value="2" data-imagesrc="images/Alignment_2.png">Right</option>
        <option value="" disabled>33% Options</option>
        <option value="3" data-imagesrc="images/Alignment_3.png">Left</option>
        <option value="4" data-imagesrc="images/Alignment_4.png">Center</option>
        <option value="5" data-imagesrc="images/Alignment_5.png">Right</option>
        <option value="" disabled>25% Options</option>
        <option value="6" data-imagesrc="images/Alignment_6.png">Left</option>
        <option value="7" data-imagesrc="images/Alignment_7.png">Center-Left</option>
        <option value="8" data-imagesrc="images/Alignment_8.png">Center-Right</option>
        <option value="9" data-imagesrc="images/Alignment_9.png">Right</option>
    </select>

I also fixed up what looked to be a mistake in the values, because from 7 the numbers stopped matching the image numbers.

That now lets someone without JavaScript select 50% from the first select, then go to the second select and easily find the 50% options to choose from.

My next post will be about how we communicate to JavaScript about which options belong to what category. It might be different from what you may think, too.

1 Like