I want to show the number of divs that have been added inside the div with the id box . I would also like to know how to add the div
ones with buttons, since the ones shown here are added by clicking on them.
jQuery(document).ready(function() {
jQuery('#productos').on('click', '.producto', function() {
var e = $(this).clone();
var identificador = $(this).attr("iden");
if ($("#caja").find("."+identificador).length) {
alert("Ya fue añadido");
} else {
jQuery(e).appendTo('#caja');
}
});
jQuery('#caja').on('click', '.producto', function() {
jQuery(this).remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="productos" style="background: #ddd; width: 50%;">
<div class="producto 1" iden="1">producto 1</div>
<div class="producto 2" iden="2">producto 2</div>
<div class="producto 3" iden="3">producto 3</div>
</div>
<div id="caja" style='background: #000; color: #fff; width: 50%;'></div>
<!-- quiero que la cantidad se muestre dentro de esta etiqueta -->
<span id='quanty'></span>
If you want to get the total of div's in your container, it would be enough to get the
length
one from the collection of elements that the selector returnsJQuery
, for your example the selector will be, all the elements with the class product'.producto'
If you want to add data to your elements, ideally you should use data attributes , (in Jquery the value is obtained with .data('identifier') , it will refer to data-identifier="somevalue" )
eg
If you want to have independent buttons to add the div's , you can change the listener so that it has the parent element
document
, then using the data attributes, get the element to add. (code explained)Here is an example of what it would look like: