【问题标题】:Faking checkbox behaviour with Bootstrap buttons-checkbox?使用引导按钮复选框伪造复选框行为?
【发布时间】:2019-08-10 18:18:23
【问题描述】:

我正在尝试使用 Bootstrap 的 data-toggle 属性来允许用户选择权限级别。

我整理了一个simple demo on JSFiddle,预期值为:

  • 无:0
  • 用户:1
  • 管理员:2
  • 用户 + 管理员 = 3

问题在于计算的值似乎比实际切换按钮落后一步。

我很确定这是一个非常简单的问题,但到目前为止,我还没有找到解决方案。


显然,我需要在此处复制 JSFiddle 代码:

$(document).ready(function () {
    $('#privileges button').click(function () {
        var privileges = 0;

        //$(this).addClass('active');

        $('#privileges button').each(function () {
            if ($(this).hasClass('active')) {
                privileges += parseInt($(this).attr('value'));
            }
        });

        $('input[id="user[privileges]"]').val(privileges);
    });
});

还有 HTML:

<label for="user[privileges]">Privileges</label>
<input id="user[privileges]" name="user[privileges]" type="text" value="0">
<div id="privileges" class="btn-group" data-toggle="buttons-checkbox" style="width: 100%;">
    <button type="button" class="btn" style="width: 50%;" value="1">User</button>
    <button type="button" class="btn" style="width: 50%;" value="2">Administrator</button>
</div>

【问题讨论】:

    标签: javascript jquery twitter-bootstrap checkbox jquery-events


    【解决方案1】:

    试试这个代码

    $(document).ready(function () {
        $('#privileges button').click(function () {
            var privileges = 0;
            var alredySelected = $(this).hasClass('active');
    
            //$(this).addClass('active');
    
            $('#privileges button').each(function () {
                if ($(this).hasClass('active')) {
                    privileges += parseInt($(this).attr('value'));
                }
            });
            if(alredySelected){
                privileges = parseInt(privileges) - parseInt($(this).val());
            } else {
                privileges = parseInt(privileges) + parseInt($(this).val());
            }
    
            $('input[id="user[privileges]"]').val( privileges);
        });
    
    
    });
    

    http://jsfiddle.net/28xsr/1/

    【讨论】:

      猜你喜欢
      • 2016-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      相关资源
      最近更新 更多