I am using Twitter Bootstrap's Javascript radio toggle buttons and want to get form input based on the state of the toggle.
The simplest approach I could find is to add an invisible tag within the buttons -- here's the helpful jsFiddle example that someone threw up.
It works nicely, but it's still sort of a kludge. My question is: what's the clean way to get form input from these buttons, i.e. without the extra hidden radio inputs?
I am using Twitter Bootstrap's Javascript radio toggle buttons and want to get form input based on the state of the toggle.
The simplest approach I could find is to add an invisible tag within the buttons -- here's the helpful jsFiddle example that someone threw up.
It works nicely, but it's still sort of a kludge. My question is: what's the clean way to get form input from these buttons, i.e. without the extra hidden radio inputs?
Share Improve this question edited Jul 13, 2012 at 17:39 Ghopper21 asked Jul 13, 2012 at 17:03 Ghopper21Ghopper21 10.5k12 gold badges65 silver badges92 bronze badges3 Answers
Reset to default 10How about
$(this).children('input[name="is_private"]').val()
DEMO
I think I misread your question the first time... You can create a hidden form element (you need it to access the value when you submit the form unless you do AJAX) and use JS to set its value.
HTML
<input type="hidden" name="status" id="status" value="" />
JS
$('div.btn-group button').click(function(){
$("#status").attr('value', $(this).attr('id'));
})
DEMO
Actually you can avoid the html input element and the css using the index()
function like this:
$('div.btn-group .btn').click(function(){
if ($(this).index() != $('div.btn-group .btn.active').index()){
alert($(this).index());
}
});
I also added a condition to not get the alert if the active button is already selected.
A solution that works well with plain form POST as well as AJAX is to have a hidden input field that represents the current state of the button group. You can then handle all these button groups the same using the following markup structure:
<form>
<div id="test-group" class="btn-group" data-toggle="buttons-radio" data-toggle-name="testOption">
<input type="hidden" name="testOption"/>
<button type="button" class="btn" data-toggle-value="one">One</button>
<button type="button" class="btn" data-toggle-value="two">Two</button>
</div>
</form>
And the following Javascript to setup any button groups on a page:
$(function () {
$('div.btn-group[data-toggle-name]').each(function () {
var group = $(this);
var form = group.parents('form').eq(0);
var name = group.attr('data-toggle-name');
var hidden = $('input[name="' + name + '"]', form);
$('button', group).each(function () {
$(this).on('click', function () {
hidden.val($(this).data("toggle-value"));
});
});
});
});
Try it out on jsFiddle