首页 > 解决方案 > 如何显示在 data-id 属性中选中的复选框

问题描述

我找到了这段代码:

var checkboxes = $('input[type=checkbox]');
checkboxes.on('change', function() {
  $('#divfilter').text(function() {
    return checkboxes.filter(':checked').map(function() {
      return this.name;
    }).get()    
    .join(', ') + '.';
  });
});
<input type="checkbox" name="barbecue" id="barbecue" value="oui" class="barbecue" />
<input type="checkbox" name="handicap" id="handicap" value="oui" class="handicap" />
<input type="checkbox" name="animaux" id="animaux" value="oui" class="animaux" />

<div id="divfilter"></div>

它工作得很好,但我需要在 data-namevar="HERE" 中显示数据:

<button
  data-namevar="I NEED CHECKBOX CHECKED SHOW HERE"
  class="add-to-cart btn_1 gradient medium full-width">Add to cart <i class="icon_bag_alt"></i>
</button>

怎么做?

标签: javascripthtmljquery

解决方案


你能试试这个吗?

var checkboxes = $('input[type=checkbox]');
checkboxes.on('change', function() {
  $('#divfilter').text(function() {
    return checkboxes.filter(':checked').map(function() {
      return $(this).attr('data-namevar');
    }).get()    
    .join(', ') + '.';
  });
});

推荐阅读