getelementbyid for buttons

Hi,

I have a products list that i am displaying in my page and for each product i have a button “add to cart”
and at the end of the page i have a button that if clicked i want to trigger auto click for the above buttons and add the products to cart in one click.

products:

{% for product in theproducts %}

	<div class="col-lg-6">
		<video class="thumbnail" width="320" height="240" controls>
	  		<source src='{{product.video_demo}}' type="video/mp4">
		</video>

		<div class="box-element product">
			<h5>{{product.name}}</h6>
			<br/>
			<h6><strong>{{product.category}}</strong></h5>
			<hr>

			{% if product.price > 0 %}

			   <button  id="product" data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>

			{% else %}

				<a href= '{{product.video_file}}' download='{{product.name}}'>
				<button  class="btn btn-outline-secondary add-btn">Download Video</button></a>

			{% endif %}		

			<h4 style="display: inline-block; float: right"><strong>AED{{product.price}}</strong></h4>
	    </div>
     </div>

     <br/>

{% endfor %}

then i have the last button outside the loop so it is not repeated:

<div><input id="secondaryButton" type="button" name="savebutton" onclick="document.getElementById('product').click()" /></div>

what happened is that only the first button is clicked for the first product. I need all the buttons to be clicked.

How to acheive that?

Thanks.

Correct - the id attribute should be unique on a page, it’s not valid to have multiple elements on a page with the same id.

You’ve got a couple different options - you can use getElementsByClassName, or querySelectorAll for a more generalized solution. Or, if you want (need) to get really fancy, you can use the evaluate function on an XPath expression.

1 Like

I used elementsbyclassname

cost collection = document.getElementByClassName('text');
for (let i = 0; i < collection.length; I++) {
    collection [I].click()
}

This is how I make like/dislike button

                                <a href="#"  onClick="document.getElementById('{{post.id}}like').submit()" ><i class="fas fa-thumbs-up"></i></a> {{post.likes}}   |   <a href="#" onClick="document.getElementById('{{post.id}}dislike').submit()"><i class="fas fa-thumbs-down"></i></a> {{post.dislikes}}


                                <form id="{{post.id}}like" method="POST" action="{% url 'postpreference' post.id 1 %}">
                                {% csrf_token %}
                                <input type="hidden">
                                </form>

                                <form id="{{post.id}}dislike" method="POST" action="{% url 'postpreference' post.id 2 %}">
                                {% csrf_token %}
                                <input type="hidden">
                                </form>