实现中间复选框状态

时间:2016-05-22 10:36:53

标签: checkbox materialize

如何让复选框显示为"不确定"什么时候在Materialise中取消选中?

HTML:

<input type="checkbox" id="test" checked/>
<label for="test" id="test-label">Red</label>

JS:

$('#test-label').click(function() {
    var checkbox = $(this).prev();
    if (!$(checkbox).is(':checked'))
        $(checkbox).prop('indeterminate', true);
});

https://jsfiddle.net/Lhwkfb75/8/

2 个答案:

答案 0 :(得分:3)

应该是indeterminate而不是intermediate。你可能因为类似的拼写而感到困惑。

$('#test').click(function() {
    if (!$(this).is(':checked'))
        $(this).prop('indeterminate', true);
});

答案 1 :(得分:0)

实现这一目标有两件事是重要的:

  1. 防止默认处理程序
  2. 设置不确定状态时,您还必须禁用选中状态,否则虽然复选框显示为中间,但$(chk).prop('checked')仍为true
  3. 您好

    $('#check-label').click(function(e) {
        e.preventDefault();
    
        var chk = $("#test");
    
        if ($(chk).prop( "checked" )) {
            $(chk).prop( "indeterminate" , true );
            $(chk).prop( "checked" , false );
        } else {
            $(chk).prop( "checked" , true );
            $(chk).prop( "indeterminate" , false );
        }
    
    });
    

    甚至更优雅:

    $('#check-label').click(function(e) {
        e.preventDefault();
    
        var chk = $("#test");
    
        $(chk).prop("checked", !$(chk).prop("checked"));
        $(chk).prop("indeterminate", !$(chk).prop("checked"));
    
    });
    

    请参阅working fiddle