简体   繁体   中英

how to get currently selected values from material_select() with jquery

The latest version of materialize has a nice looking multi-select implementation with checkboxes next to the options that are currently selected. But once an item has been selected, I don't seem to be able to un-select it again. The visible check mark goes away, but jquery still thinks it's selected. Here's the short example below (it doesn't look like materialize0.97.2's material_select works at all in jsfiddle, sorry). Once you show one of the two divs, you can't hide it again.

<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.2/css/materialize.min.css">
</head>
<body>
<div class="container">
    <div class="row">
        <form>
            <div class="input-field col s3" style="margin-left: 50px">
                <select multiple id="column-selector">
                    <option value="" selected disabled>your choice</option>
                    <option value="first">first</option>
                    <option value="second">second</option>
                </select>
            </div>
        </form>
    </div>
    <div class="row col s1">
        <div class="first hide">first</div>
        <div class="second hide">second</div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.2/js/materialize.min.js"></script>
<script>
$(document).ready(function() {
    /* this activates the "which columns to display" selectbox */

    $('#column-selector').on('change',function() {
        var selectedList = $(this).val();
        var currentlySelected = {};
        for (i in selectedList){
            var colName = selectedList[i];
            currentlySelected[colName] = true;
        }
        var colNames = [ "first", "second" ];
        for (var i in colNames){
            colname = colNames[i];
            if (currentlySelected[colname]){
                 console.log('showing ' + colname);
                 $( '.' + colname).removeClass('hide');
            }else{
                 console.log('hiding ' + colname);
                 $( '.' + colname).addClass('hide');
            }
         }
    });
    $('#column-selector').material_select();
});
</script>


</body>
</html>

Is there a better/more correct/working way to get the currently selected values of the material_select selectbox?

I did this, but it's not necessarily the best way.

Updating/Destroying Select

$('select').material_select('destroy');

Reinitialization

$('select').material_select();

Hopefully this helps ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM