我正在使用以下HTML代码创建按钮。我已经将类从引导程序应用于这些按钮。
<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>
现在我想要的是用户选择的按钮的值。表示如果用户选择按钮1,那么我想要按钮1的相关值。如果他只选择按钮2,那么我应该得到按钮2的相关值,如果用户选择了两个按钮,那么我应该得到两个按钮的值。为了实现这一点,我尝试了以下代码,但是没有用。有人可以帮我解决这个问题吗?提前致谢。
$('.monibtn').click(function(){
var selected = [];
$('.monibtn').each(function(){
if($('.monibtn').hasClass('active')) {
selected.push($(this).val());
$('#revenueSource1').val(selected);
}
});
});
最佳答案
您可以将.map()与目标选择器.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());
});