Please tell me how you can when choosing a checkbox to take their value and add a button to the onclick through a space, and when you remove a certain checkbox, its value was removed

<div class="products-cont"> <div class="products"> <input id="product-1" type="checkbox" name="checkboxlist" value="add('1');"> <input id="product-2" type="checkbox" name="checkboxlist" value="add('2');"> <input id="product-3" type="checkbox" name="checkboxlist" value="add('3');"> <input id="product-4" type="checkbox" name="checkboxlist" value="add('4');"> </div> <div class="btn-cont"> <button type="button" class="btn btn-main prod-btn-1" onclick="add('8');">Добавить</button> </div> </div> 

I would be very grateful for any help.

  • "add a button to onclick separated by a space" - ?? - Igor
  • @Igor yes, space separated, like this onclick = "add ('1'); add ('3'); add ('8');" - Makissm

1 answer 1

I think that the "gap" has nothing to do with it.

 function add(a) { console.log(a); } $("input[type='checkbox']").click(function() { var $btn = $('.prod-btn-1'); if (this.checked) { $btn.attr("onclick", $btn.attr("onclick") + this.value); } else { $btn.attr("onclick", $btn.attr("onclick").replace(this.value, "")); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="products-cont"> <div class="products"> <input id="product-1" type="checkbox" name="checkboxlist" value="add('1');"> <input id="product-2" type="checkbox" name="checkboxlist" value="add('2');"> <input id="product-3" type="checkbox" name="checkboxlist" value="add('3');"> <input id="product-4" type="checkbox" name="checkboxlist" value="add('4');"> </div> <div class="btn-cont"> <button type="button" class="btn btn-main prod-btn-1" onclick="add('8');">Добавить</button> </div> </div>