0

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);
                }
            });
        });
1
  • 2
    IDs must be unique. You have two elements with the same ID in your code. Commented Jan 16, 2014 at 10:19

1 Answer 1

1

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());
});
Sign up to request clarification or add additional context in comments.

1 Comment

@NoobEditor it returns a new jQuery object which contains the value returned by the callback function see api.jquery.com/map

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.