如何使用jquery从material_select()获取当前选定的值

时间:2015-11-14 19:33:53

标签: javascript jquery materialize

最新版本的materialize有一个漂亮的多选实现,当前选中的选项旁边有复选框。但是一旦选择了一个项目,我似乎无法再次取消选择它。可见的复选标记消失,但jquery仍认为它已被选中。这是下面的简短示例(它看起来不像materialize0.97.2的material_select在jsfiddle中完全有效,抱歉)。一旦你显示了两个div中的一个,你就无法再次隐藏它。

<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>

是否有更好/更正确/更有效的方式来获取material_select选择框的当前选定值?

1 个答案:

答案 0 :(得分:1)

我这样做了,但这不一定是最好的方式。

更新/销毁选择

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

重新初始化

$('select').material_select();

希望这会有所帮助;)