Vika
Vika

Reputation: 163

jQuery - get active button from buttons group (input type = "radio")

I'm using bootstrap buttons, which look like regular buttons but they act like radio.

<div class="btn-group-horizontal" data-toggle="buttons" id ="Group">
  <label class="btn btn-sm btn-info btnSelect active">
    <input type="radio" name="options" id="Option 1" autocomplete="off" checked> Option 1
  </label>
  <label class="btn btn-sm btn-info btnSelect">
    <input type="radio" name="options" id="Option 2" autocomplete="off"> Option 2
  </label>
</div>

How can I get the ID / text of the active button?

Thanks!

Upvotes: 2

Views: 13463

Answers (3)

Vika
Vika

Reputation: 163

The solution was the following:

I had to change the HTML by addiong ID to the lable

<div class="btn-group-horizontal" data-toggle="buttons" id ="Group">
  <label class="btn btn-sm btn-info btnSelect active" **id="Option 1"**>
    <input type="radio" name="options" id="Option 1" autocomplete="off" checked> Option 1
  </label>
  <label class="btn btn-sm btn-info btnSelect" **id="Option 2"**>
    <input type="radio" name="options" id="Option 2" autocomplete="off"> Option 2
  </label>
</div>

and by using following jQuery:

var answer= '';
            $('#Group .active').each(function(){
                answer= $(this).attr('id'); 
            }); 

Upvotes: 11

Rob Schmuecker
Rob Schmuecker

Reputation: 8954

You can just use a simple CSS selector

$(document).ready(function () {
    alert($('.active input').prop('id'));
});

Demo: http://jsfiddle.net/robschmuecker/L7maoufy/

Upvotes: 6

MH2K9
MH2K9

Reputation: 12039

Can try using each() & is(). Example:

var activeId = '';
$('input[type=radio]').each(function(){
    if($(this).is(':checked')){
        activeId = $(this).attr('id'); 
        //alert(activeId);
        return false;
    }
});

Upvotes: 1

Related Questions