Reputation: 36639
The JavaScript page for Bootstrap shows some nice use of buttons to style checkboxes and radio fields. For example, for a checkbox, I might write
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input type="checkbox"> Option 1
</label>
</div>
However, the library doesn't actually change the value of the underlying <input>
field -- it just changes whether the <label>
field has class active
. I would have expected it to change the checked
attribute on the checkbox. Apparently I don't just have it misconfigured -- this is the way the examples on the Bootstrap site work.
Is this actually expected behavior? If so, it seems fairly useless, as people are going to want to use the checkbox field. If not, how do I properly configure Bootstrap checkboxes/radio buttons?
Upvotes: 22
Views: 47263
Reputation: 2534
The checked
attribute on the input isn't modified because that isn't what changes when a checkbox input is checked -- the checked
DOM property is what changes (true or false), and Bootstrap handles this properly (you can inspect the element in Firebug and see the DOM property change when you toggle them). The checked
attribute is only used to determine default value when the DOM is initially rendered.
If you ever happen to be doing any js/jQuery with checkboxes/radios, remember this! If you need to programatically check a checkbox or radio button, $('input').attr('checked', 'checked');
will not get the job done. $('input').prop('checked', true);
is what you need.
This isn't special behavior for Bootstrap buttons, this is how all checkbox/radios work.
Edit: Firebug screenshot
Edit 2: Added text from the comments, as it seems to be helpful.
Upvotes: 39
Reputation: 8599
I am doing it like this for MVC.NET in case anyone needs it:
@{
var removeSelected = Model.Remove == true ? "active" : "";
var buttonText = Model.Remove == true ? "Add" : "Remove";
}
@Html.HiddenFor(model => model.Remove)
<div class="editor-field">
<div class="btn-group" data-toggle="buttons-checkbox">
<button type="button" id="RemoveButton" class="btn btn-primary @removeSelected" onclick="toggle();">@buttonText</button>
</div
</div>
function toggle() {
var value = $("#Remove").val();
if (value == "False") {
$("#Remove").val("True");
$("#RemoveButton").text("Add");
}
else {
$("#Remove").val("False");
$("#RemoveButton").text("Remove");
}
}
And finally don't forget to add the bootstrap js refence.
Upvotes: 1
Reputation: 30456
It looks like you are missing a call to "activate" the btn-group
(documentation). Here is a demo of this working:
<form id='testForm'>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input type="checkbox" name='Option' value='1' />Option 1</label>
</div>
</form>
<button class='btn' id='actionSubmit'>Submit</button>
<script>
$('#actionSubmit').on('click', function (e) {
e.preventDefault();
alert($('#testForm').serialize());
});
$('.btn-group').button();
</script>
Upvotes: 3