Search code examples
javascriptcssmaterialize

Preselecting options of multiple selectbox, using Materialize css FW doesn't work


I'm using materialize css framework. When I'm printing multiple selectbox (<select multiple>...), preselected options (<option selected...>) won't render. Browser however understand that some options are preselected, so they are send again, when the form is submited. Also because of the rendering issue i'm unable to manipulate with preselected options or select new ones.

Normal Selectbox works just fine.


Solution

  • You can add onchange event to field and reset the values by accessing all the (li) children. If you see carefully. Multi select uses UL and a text field for value storing and keeps class "Active" for li. And append this code after .material select since check boxes are initialized after that

    you can try following in

    function change_materialize_multiple_Select(id_of_select)
    {
        var newValuesArr = [],
                select = $(id_of_select),
                ul = select.prev();
            ul.children('li').toArray().forEach(function (li, i) {
                if ($(li).hasClass('active')) {
                    newValuesArr.push(select.children('option').toArray()[i].value);
                }
            });
            select.val(newValuesArr);   
    }