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 ?

Adham
  • 63,550
  • 98
  • 229
  • 344

3 Answers3

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()
Tyler Johnson
  • 927
  • 8
  • 24
  • It would actually require setting active on one and unsetting active on all others. Not a very nice interface IMO. – Josh Hansen Jun 07 '13 at 20:38
  • 1
    This is the final solution I came up with to get the selected element , `$('.btn-group > .btn.active input')[0]` – sameera207 Nov 23 '14 at 22:37
15

Here is one more solution

 alert($('.btn-group > .btn.active').text());
Shivek Parmar
  • 2,865
  • 2
  • 33
  • 42
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);
});
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247