1

I'm trying to use the data-toggle attribute of Bootstrap to allow the user to select the privilege level.

I have put together a simple demo on JSFiddle, the expected values are:

  • None: 0
  • User: 1
  • Administrator: 2
  • User + Administrator = 3

The problem is that the computed value seems to be one step behind of the actual toggled buttons.

I'm pretty sure this is a pretty simple problem, but so far the solution has managed to elude me.


Apparently, I'm required to duplicate the JSFiddle code here:

$(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);
    });
});

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

1 Answer 1

3

Try this code

$(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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.