最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin9浏览0评论

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" autoplete="off" checked> Option 1
  </label>
  <label class="btn btn-sm btn-info btnSelect">
    <input type="radio" name="options" id="Option 2" autoplete="off"> Option 2
  </label>
</div>

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

Thanks!

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" autoplete="off" checked> Option 1
  </label>
  <label class="btn btn-sm btn-info btnSelect">
    <input type="radio" name="options" id="Option 2" autoplete="off"> Option 2
  </label>
</div>

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

Thanks!

Share Improve this question edited Dec 7, 2014 at 14:40 lukasgeiter 153k29 gold badges349 silver badges280 bronze badges asked Dec 7, 2014 at 9:39 VikaVika 1631 gold badge1 silver badge10 bronze badges 1
  • 1 possible duplicate of How can I get which radio is selected via jQuery? – Igor Kustov Commented Dec 7, 2014 at 9:44
Add a ment  | 

3 Answers 3

Reset to default 11

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" autoplete="off" checked> Option 1
  </label>
  <label class="btn btn-sm btn-info btnSelect" **id="Option 2"**>
    <input type="radio" name="options" id="Option 2" autoplete="off"> Option 2
  </label>
</div>

and by using following jQuery:

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

You can just use a simple CSS selector

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

Demo: http://jsfiddle/robschmuecker/L7maoufy/

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;
    }
});
发布评论

评论列表(0)

  1. 暂无评论