JSFiddle - React, Tailwind, and code Playground

by JudaPriest

HTML

<select id="edit-field-ville-tid" class="form-select" name="field_ville_tid">
    <option selected="selected" value="All">Toutes les zzzilles</option>
    <option value="1">Pâque</option>
    <option value="2">Île</option>
    <option value="3">Maurice</option>
    <option value="4">Réunion</option>
    <option value="6">Requin ?</option>
    <option value="7">Sacre-bleu</option>
    <option value="5">Passembleu</option>
</select>
<br />
<br />
<p> Todo : </p>
<ul>
  <li>Add an "else condition" in case arg name is null</li>
  <li>I'm sure some optimization is possible</li>
  <li>Get some milk for tomorow morning</li>
</ul> 
<p> Fucking easy to use : </p>
<pre> $( YOUR SELECT ID HERE ).convertIntoUl( THE VALUE THAT WILL BE DISPLAYED ) </pre>
It will convert your select into an ul list, on wich you can add any CSS style, and you just have to "display : none;" the original select. Hat Trick !

CSS

#edit-field-ville-tid {
    display : none;
}
p{
    color:red;
}

JavaScript

(function ($) {
    $.fn.convertIntoUl = function (name) {
        var $origSelect = $(this);
        var selectId = '#' + $(this).attr('id');
        var newId = selectId + '-ul';

        if (name.length > 0) {
            // Copy select content into an ul list
            var out = '<div id="' + newId.substring(1) + '"><span>' + name + '</span>';
            out += '<ul>';
            $(selectId + ' > option').each(function () {
                out += '<li><a href="">' + $(this).html() + '</a></li>';
            });
            out += '</ul>';
            out += '</div>';

            $(out).insertBefore(selectId);
            $(newId + ' ul').hide();
        } //END IF

        $(newId + ' li:not(":first")').addClass('unselected');
        //add class unselected to all li except the 1rst child    

        $(newId).find('li').click(

        function () {
            $('.unselected').removeClass('unselected');
            // remove unselected 

            $(this).siblings('li').addClass('unselected');
            // add unselected à tout les autres li

            var index = $(this).index();
            var name = $(this).text();
            
            $($origSelect).removeAttr('selected');
            // deselects the previously-chosen-one (the Messi !) option

            $($origSelect)
                .find('option:eq(' + index + ')')
                .attr('selected', true);
            // create a link between the select and the ul list

            $(newId + ' span').text(name); // remplace le texte du span
            $(newId + ' ul').toggle();
            return false; //Evite de refresh la page 'cuz <a> tag
        });

        $(newId + ' span').click(function () {
            $(newId + ' ul').toggle();
        });
    }
})(jQuery);


$('#edit-field-ville-tid').convertIntoUl('Clique-moi mon chou ! ');