从所选项目中添加单独的div

时间:2018-04-15 23:58:59

标签: jquery

单击提交按钮时,我尝试仅显示所选项目的文本。我遇到的问题是将所有选定的项目放入单个<div>元素中。有没有办法让每个选定的项目都进入他们自己的<div>元素?

以下是可以选择的按钮项的html:

<div class="select-group">
    <p class="item-selection">item 1</p><button type="button" class="btn btn-default check">Add Item</button>
    <p class="item-selection">item 2</p><button type="button" class="btn btn-default check">Add Item</button>
    <p class="item-selection">item 3</p><button type="button" class="btn btn-default check">Add Item</button>
</div>

<a class="submit-ct" href="#">
  Submit Order
</a>

这是jquery:

$('.submit-ct').on('click', function(){
  if ( $( '.btn' ).hasClass( 'active' ) ) {
    var itemSelected = $( '.btn.active' ).prev().text();
    $("<div>"+itemSelected+"</div>").attr('class', 'item-list-select').appendTo(".item-list");
  } 
})

2 个答案:

答案 0 :(得分:1)

尝试:

&#13;
&#13;
$('.select-group').on('click', '.btn', function() {
  var btn = $(this);
  if (btn.hasClass('active')) {
    btn.removeClass('active');
  } else {
    btn.addClass('active');
  }
});

$('.submit-ct').on('click', function(){
  var itemSelected = $( '.btn.active' ).prev().text();
  if (!itemSelected) return;
  $("<div>"+itemSelected+"</div>").attr('class', 'item-list-select').appendTo(".item-list");
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-group">
    <p class="item-selection">item 1</p><button type="button" class="btn btn-default check">Add Item</button>
    <p class="item-selection">item 2</p><button type="button" class="btn btn-default check">Add Item</button>
    <p class="item-selection">item 3</p><button type="button" class="btn btn-default check">Add Item</button>
</div>

<h3>selected:</h3>
<div class="item-list"></div>

<a class="submit-ct" href="#">
  Submit Order
</a>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用each()

找到解决方案
$('.submit-ct').on('click', function(){
    $( '.btn.active' ).each(function() {
      var itemSelected = $( this ).prev().text();
      $("<div>"+itemSelected+"</div>").attr('class', 'item-list-select').appendTo(".item-list");
    });
})