Ad

Get Value Multiple Button Created By Checked Checkbox

- 1 answer

I want to get value from button. This button appear when checkbox checked.

if only one button, it's ok, but when there is so many button it will fetch last button data-attr which is not good

$('#other-products').on('change', function() {
    var selectedProducts = [];
    var listProductsCtrl = $('.list-products');
    listProductsCtrl.html('');
    $('#other-products input[type="checkbox"]:checked').each(function() {
      selectedProducts.push($(this).attr('name'));
      var showtimesAsString = '<button class="number" data-label="'+$(this).attr('name')+'">'+selectedProducts.join('</button> <button class="test">')+'</button>';
      listProductsCtrl.html(showtimesAsString);
      
    });
    $('.number').click(function(){
    		
      	alert($(this).attr('data-label'));
      
      });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="other-products">
  <input type="checkbox" name="First" value="1">
  <input type="checkbox" name="Second" value="2">
  <input type="checkbox" name="Third" value="3">
</div>
<span class="list-products"></span>

Ad

Answer

for 2nd and 3rd you are appending class test not number, and that does not having data-label attribute

SO here i just display text() here.

$('#other-products').on('change', function() {
    var selectedProducts = [];
    var listProductsCtrl = $('.list-products');
    listProductsCtrl.html('');
    $('#other-products input[type="checkbox"]:checked').each(function() {
      selectedProducts.push($(this).attr('name'));
      var showtimesAsString = '<button class="number" data-label="'+$(this).attr('name')+'">'+selectedProducts.join('</button> <button class="test">')+'</button>';
      listProductsCtrl.html(showtimesAsString);
      
    });
    $('.number, .test').click(function(){
    		
      	alert($(this).text());
      
      });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="other-products">
  <input type="checkbox" name="First" value="1">
  <input type="checkbox" name="Second" value="2">
  <input type="checkbox" name="Third" value="3">
</div>
<span class="list-products"></span>

Ad
source: stackoverflow.com
Ad