Reputation: 154513
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:
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>
Upvotes: 1
Views: 2184
Reputation: 2158
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);
});
});
Upvotes: 3