简体   繁体   中英

How to get value/values of buttons created using twitter bootstrap?

I'm using the following HTML code for button creation. I've applied the classes from bootstrap to these buttons.

<label class="help-block" for="xlInput">Monetization</label>
<div id="revsource" class="btn-group" data-toggle="buttons-checkbox">
<button id="revenueSource" class="btn monibtn active" value="1" data-toggle="button" type="button">Advertise</button>
<button id="revenueSource" class="btn monibtn" value="2" data-toggle="button" type="button">License</button>
<div class="controls">
<input id="revenueSource1" type="hidden" 0="0" name="data[RevenueSource][revenue_source_id]" value="1,2">
</div>
</div>

Now what I want is the value or values of the buttons selected by user. Means if user selects button 1 then I want the concerned value of button 1. If he selects button 2 only then the concerned value of button 2 I should get and if user selects both the buttons then I should get the values of both buttons. For achieving this I tried following code but it didn't work. Can anyone please help me out in this thing? Thanks in advance.

$('.monibtn').click(function(){
            var selected = [];
            $('.monibtn').each(function(){
                if($('.monibtn').hasClass('active')) {
                    selected.push($(this).val());
                    $('#revenueSource1').val(selected);
                }
            });
        });

You can use .map() along with the target selector .monibtn.active

$('.monibtn').click(function () {
    //get all .monibtn elements with class active and create an array with the value of those elements
    var selected = $('.monibtn.active').map(function () {
        return this.value;
    }).get();
    //assing the value of the selected array to the target element
    $('#revenueSource1').val(selected.join());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM