How to get the value of selected button in twitter bootstrap button group
Asked Answered
K

3

15

If I haev a radio button group in bootstrap like the following :

<div class="btn-group" data-toggle="buttons-radio">
        <button class="btn">1</button>
        <button class="btn">2</button>
        <button class="btn">3</button>
        <button class="btn">4</button>
</div>

How can I get/ set the selected value ?

Kigali answered 8/6, 2012 at 0:17 Comment(0)
A
12
var num = null;
var ele = document.querySelectorAll(".btn-group > button.btn");
for(var i=0; i<ele.length; i++){
    ele[i].addEventListener("click", function(){
        num = +this.innerHTML;
        alert("Value is " + num);
    });
}

Or jQuery:

var num = null;
$(".btn-group > button.btn").on("click", function(){
    num = +this.innerHTML;
    alert("Value is " + num);
});
Alterant answered 8/6, 2012 at 0:29 Comment(2)
Thanks, but how to set the value the groupKigali
@Kigali - this.innerHTML = valueUnderhand
K
16

To set the active element, add the class active to whichever button you want selected (and deselect the rest).

$('.btn-group > .btn').removeClass('active')    // Remove any existing active classes
$('.btn-group > .btn').eq(0).addClass('active') // Add the class to the nth element

To get the html/text content of the currently active button, try something like this:

$('.btn-group > .btn.active').html()
Kennithkennon answered 23/10, 2012 at 18:56 Comment(2)
It would actually require setting active on one and unsetting active on all others. Not a very nice interface IMO.Hollishollister
This is the final solution I came up with to get the selected element , $('.btn-group > .btn.active input')[0]Statistical
G
15

Here is one more solution

 alert($('.btn-group > .btn.active').text());
Guyon answered 1/3, 2014 at 12:38 Comment(0)
A
12
var num = null;
var ele = document.querySelectorAll(".btn-group > button.btn");
for(var i=0; i<ele.length; i++){
    ele[i].addEventListener("click", function(){
        num = +this.innerHTML;
        alert("Value is " + num);
    });
}

Or jQuery:

var num = null;
$(".btn-group > button.btn").on("click", function(){
    num = +this.innerHTML;
    alert("Value is " + num);
});
Alterant answered 8/6, 2012 at 0:29 Comment(2)
Thanks, but how to set the value the groupKigali
@Kigali - this.innerHTML = valueUnderhand

© 2022 - 2024 — McMap. All rights reserved.