Enable and disable button for dynamic elements in cart

Asked

Viewed 330 times

0

I created these functions in case the quantity of the product is changed, regardless of whether it is by the arrow buttons or directly in the field, the "Update" button appears, only for the product that underwent the change. However, if I change 1 product, the button appears for all others. And when I click on the same product again, the button removes it, but adds another button on another product.

inserir a descrição da imagem aqui

<form action="http://.../checkout/cart/updatePost/" method="post" id="form-validate" class="form form-cart">
      <input name="form_key" type="hidden" value="rW5XuwwQiEurJLOt">
      <div class="cart table-wrapper">
        <table id="shopping-cart-table" class="cart items data table">
          <caption role="heading" aria-level="2" class="table-caption">Itens do Carrinho de Compras</caption>
          <thead>
            <tr>
              <th class="col item" scope="col"><span>Item</span></th>
              <th class="col price" scope="col"><span>Preço</span></th>
              <th class="col qty" scope="col"><span>Qtd</span></th>
              <th class="col subtotal" scope="col"><span>Subtotal</span></th>
            </tr>
          </thead>
          <tbody class="cart item">
            <tr class="item-info">
              <td data-th="Item" class="col item">
                <a href="http://.../estojo-lowcost-azul-lentes-de-contato.html" title="Estojo para lentes de contato Bausch &amp; Lomb&lrm; azul" tabindex="-1" class="product-item-photo">

                  <span class="product-image-container" style="width:165px;">
            <span class="product-image-wrapper" style="padding-bottom: 100%;">
                <img class="product-image-photo" src="http://.../pub/media/catalog/product/cache/3a98496dd7cb0c8b28c4c254a98f915a/c/b/cbl.jpg" max-width="165" max-height="165" alt="Estojo para lentes de contato Bausch &amp; Lomb&lrm; azul"></span>
                  </span>
                </a>
                <div class="product-item-details">
                  <strong class="product-item-name">
                      <a href="http://.../estojo-lowcost-azul-lentes-de-contato.html">Estojo para lentes de contato Bausch &amp; Lomb&lrm; azul</a>
                  </strong>
                </div>
              </td>
              <td class="col price" data-th="Preço">

                <span class="price-excluding-tax" data-label="Excl. Impostos">
                  <span class="cart-price">
                     <span class="price">R$4,90</span> 
                  </span>
                </span>
              </td>
              <td class="col qty" data-th="Qtd">
                <div class="field qty">
                  <label class="label" for="cart-2217-qty">
                            <span>Qtd</span>
                        </label>
                  <div class="control qty">
                    <input id="cart-2217-qty" name="cart[2217][qty]" data-cart-item-id="1530" value="4" type="number" size="4" title="Qtd" class="input-text qty" maxlength="12" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty">
                  </div>
                  <div class="qty-changer">
                    <a href="javascript:void(0)" class="qty-inc"><i class="porto-icon-up-dir"></i></a>
                    <a href="javascript:void(0)" class="qty-dec"><i class="porto-icon-down-dir"></i></a>
                  </div>
                </div>
              </td>

              <td class="col subtotal" data-th="Subtotal">

                <span class="price-excluding-tax" data-label="Excl. Impostos">
                     <span class="cart-price">
                          <span class="price">R$19,60</span>                            </span>
                </span>
              </td>
            </tr>
            <tr class="item-actions">
              <td colspan="100">
                <div class="actions-toolbar">
                  <div id="gift-options-cart-item-2217" data-bind="scope:'giftOptionsCartItem-2217'" class="gift-options-cart-item">
                    <!-- ko template: getTemplate() -->
                    <!-- ko if: isActive() || hasActiveOptions() -->
                    <!-- /ko -->
                    <!-- /ko -->

                  </div>
                  <a class="action action-edit" href="http://.../checkout/cart/configure/id/2217/product_id/64518/" title="Editar parâmetros do item">
                    <span>
                    Editar        </span>
                  </a>
                  <a href="#" title="Remover item" class="action action-delete" data-post="{&quot;action&quot;:&quot;http:\/\/...\/checkout\/cart\/delete\/&quot;,&quot;data&quot;:{&quot;id&quot;:&quot;2217&quot;,&quot;uenc&quot;:&quot;aHR0cDovLzE4LjIyOS4xNDUuODQvY2hlY2tvdXQvY2FydC8,&quot;}}">
                    <span>
                Remover item    </span>
                  </a><button id="updateCar" type="submit" name="update_cart_action" data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;"><span>Atualizar</span></button><button id="updateCar"
                    type="submit" name="update_cart_action" data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;"><span>Atualizar</span></button><button id="updateCar" type="submit" name="update_cart_action"
                    data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;"><span>Atualizar</span></button><button id="updateCar" type="submit" name="update_cart_action" data-cart-item-update=""
                    value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;"><span>Atualizar</span></button>
                </div>
              </td>
            </tr>
          </tbody>
          <tbody class="cart item">
            <tr class="item-info">
              <td data-th="Item" class="col item">
                <a href="http://.../renu-fresh-120ml.html" title="Renu Fresh 120ml " tabindex="-1" class="product-item-photo">

                  <span class="product-image-container" style="width:165px;">
            <span class="product-image-wrapper" style="padding-bottom: 100%;">
                <img class="product-image-photo" src="http://.../pub/media/catalog/product/cache/3a98496dd7cb0c8b28c4c254a98f915a/l/2/l2412989.jpg" max-width="165" max-height="165" alt="Renu Fresh 120ml "></span>
                  </span>
                </a>
                <div class="product-item-details">
                  <strong class="product-item-name">
                                                    <a href="http://.../renu-fresh-120ml.html">Renu Fresh 120ml </a>
                                            </strong>
                </div>
              </td>

              <td class="col price" data-th="Preço">

                <span class="price-excluding-tax" data-label="Excl. Impostos">
                            <span class="cart-price">
                                <span class="price">R$24,90</span> </span>

                </span>
              </td>
              <td class="col qty" data-th="Qtd">
                <div class="field qty">
                  <label class="label" for="cart-2218-qty">
                            <span>Qtd</span>
                        </label>
                  <div class="control qty">
                    <input id="cart-2218-qty" name="cart[2218][qty]" data-cart-item-id="1350" value="1" type="number" size="4" title="Qtd" class="input-text qty" maxlength="12" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty">
                  </div>
                  <div class="qty-changer">
                    <a href="javascript:void(0)" class="qty-inc"><i class="porto-icon-up-dir"></i></a>
                    <a href="javascript:void(0)" class="qty-dec"><i class="porto-icon-down-dir"></i></a>
                  </div>
                </div>
              </td>

              <td class="col subtotal" data-th="Subtotal">

                <span class="price-excluding-tax" data-label="Excl. Impostos">
                            <span class="cart-price">
                                <span class="price">R$24,90</span> 
</span>

                </span>
              </td>
            </tr>
            <tr class="item-actions">
              <td colspan="100">
                <div class="actions-toolbar">
                  <div id="gift-options-cart-item-2218" data-bind="scope:'giftOptionsCartItem-2218'" class="gift-options-cart-item">
                    <!-- ko template: getTemplate() -->
                    <!-- ko if: isActive() || hasActiveOptions() -->
                    <!-- /ko -->
                    <!-- /ko -->

                  </div>
                  <a class="action action-edit" href="http://.../checkout/cart/configure/id/2218/product_id/64516/" title="Editar parâmetros do item">
                    <span>
                    Editar        </span>
                  </a>
                  <a href="#" title="Remover item" class="action action-delete" data-post="{&quot;action&quot;:&quot;http:\/\/...\/checkout\/cart\/delete\/&quot;,&quot;data&quot;:{&quot;id&quot;:&quot;2218&quot;,&quot;uenc&quot;:&quot;aHR0cDovLzE4LjIyOS4xNDUuODQvY2hlY2tvdXQvY2FydC8,&quot;}}">
                    <span>
                Remover item    </span>
                  </a>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="cart main actions">
        <a class="action continue" href="http://.../" title="Continuar Comprando">
          <span>Continuar Comprando</span>
        </a>
        <button type="submit" name="update_cart_action" data-cart-empty="" value="empty_cart" title="Limpar Carrinho de Compras" class="action clear" id="empty_cart_button">
                    <span>Limpar Carrinho de Compras</span>
                </button>
        <input type="hidden" value="" id="update_cart_action_container" data-cart-item-update="">
      </div>
    </form>

function habilitaButton() {

 	var divTableCart = document.getElementById('shopping-cart-table');
	var itemProduct = divTableCart.getElementsByClassName('action-delete');

for(var j =0; j < itemProduct.length; j++){	
	 itemProduct[j].insertAdjacentHTML("afterend", '<button id="updateCar" type="submit" name="update_cart_action" data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update"><span>Atualizar</span></button>');
	}
}
function removeButton(){
	var divTableCart = document.getElementById('shopping-cart-table');
	var itemProduct = divTableCart.getElementsByClassName('action-delete');

	for(var l =0; l < itemProduct.length; l++){	
	 document.getElementById("updateCar").style.display="none";
	}
}


var QtdyProduct = document.getElementsByClassName("control qty");

for(var i =0; i < QtdyProduct.length; i++){	
	var qtdAlterada = QtdyProduct[i].getElementsByTagName('input')[0];
	qtdAlterada.addEventListener("blur", habilitaButton);
	
	qtdAlterada.addEventListener("focusin", removeButton);
}

  • 1

    Can you post HTML? Then you could test the code.

  • hi @Vítorferragini has yes.

2 answers

1

This is happening because at Function habilitaButton() you are going through all the "action-delete" Divs and inserting in them the Update Button, the correct is to check if the current index is the same as the one in the for.

To simplify the whole script I changed the HTML of the Update Button, changing the id "updateCar" by class in its place to be able to search for all the Buttons in Javascript and added it in all the items of the cart and also add the class "input-Qty" in all inputs of Quantity.

The HTML was as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Testes</title>
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
	<link rel="stylesheet" href="style.css">
</head>
<body>

	<form action="http://.../checkout/cart/updatePost/" method="post" id="form-validate" class="form form-cart">
      <input name="form_key" type="hidden" value="rW5XuwwQiEurJLOt">
      <div class="cart table-wrapper">
        <table id="shopping-cart-table" class="cart items data table">
          <caption role="heading" aria-level="2" class="table-caption">Itens do Carrinho de Compras</caption>
          <thead>
            <tr>
              <th class="col item" scope="col"><span>Item</span></th>
              <th class="col price" scope="col"><span>Preço</span></th>
              <th class="col qty" scope="col"><span>Qtd</span></th>
              <th class="col subtotal" scope="col"><span>Subtotal</span></th>
            </tr>
          </thead>
          <tbody class="cart item">
            <tr class="item-info">
              <td data-th="Item" class="col item">
                <a href="http://.../estojo-lowcost-azul-lentes-de-contato.html" title="Estojo para lentes de contato Bausch &amp; Lomb&lrm; azul" tabindex="-1" class="product-item-photo">

                  <span class="product-image-container" style="width:165px;">
            <span class="product-image-wrapper" style="padding-bottom: 100%;">
                <img class="product-image-photo" src="http://.../pub/media/catalog/product/cache/3a98496dd7cb0c8b28c4c254a98f915a/c/b/cbl.jpg" max-width="165" max-height="165" alt="Estojo para lentes de contato Bausch &amp; Lomb&lrm; azul"></span>
                  </span>
                </a>
                <div class="product-item-details">
                  <strong class="product-item-name">
                      <a href="http://.../estojo-lowcost-azul-lentes-de-contato.html">Estojo para lentes de contato Bausch &amp; Lomb&lrm; azul</a>
                  </strong>
                </div>
              </td>
              <td class="col price" data-th="Preço">

                <span class="price-excluding-tax" data-label="Excl. Impostos">
                  <span class="cart-price">
                     <span class="price">R$4,90</span> 
                  </span>
                </span>
              </td>
              <td class="col qty" data-th="Qtd">
                <div class="field qty">
                  <label class="label" for="cart-2217-qty">
                            <span>Qtd</span>
                        </label>
                  <div class="control qty">
                    <input id="cart-2217-qty" class="input-qty" name="cart[2217][qty]" data-cart-item-id="1530" value="4" type="number" size="4" title="Qtd" class="input-text qty" maxlength="12" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty"><!--Alterei aqui-->
                  </div>
                  <div class="qty-changer">
                    <a href="javascript:void(0)" class="qty-inc"><i class="porto-icon-up-dir"></i></a>
                    <a href="javascript:void(0)" class="qty-dec"><i class="porto-icon-down-dir"></i></a>
                  </div>
                </div>
              </td>

              <td class="col subtotal" data-th="Subtotal">

                <span class="price-excluding-tax" data-label="Excl. Impostos">
                     <span class="cart-price">
                          <span class="price">R$19,60</span>                            </span>
                </span>
              </td>
            </tr>
            <tr class="item-actions">
              <td colspan="100">
                <div class="actions-toolbar">
                  <div id="gift-options-cart-item-2217" data-bind="scope:'giftOptionsCartItem-2217'" class="gift-options-cart-item">
                    <!-- ko template: getTemplate() -->
                    <!-- ko if: isActive() || hasActiveOptions() -->
                    <!-- /ko -->
                    <!-- /ko -->

                  </div>
                  <a class="action action-edit" href="http://.../checkout/cart/configure/id/2217/product_id/64518/" title="Editar parâmetros do item">
                    <span>
                    Editar        </span>
                  </a>
                  <a href="#" title="Remover item" class="action action-delete" data-post="{&quot;action&quot;:&quot;http:\/\/...\/checkout\/cart\/delete\/&quot;,&quot;data&quot;:{&quot;id&quot;:&quot;2217&quot;,&quot;uenc&quot;:&quot;aHR0cDovLzE4LjIyOS4xNDUuODQvY2hlY2tvdXQvY2FydC8,&quot;}}">
                    <span>
                Remover item    </span>
                  </a>
				  <button class="updateCar" type="submit" name="update_cart_action" data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;"><span>Atualizar</span></button><!--Fiz a alteração aqui-->
                </div>
              </td>
            </tr>
          </tbody>
          <tbody class="cart item">
            <tr class="item-info">
              <td data-th="Item" class="col item">
                <a href="http://.../renu-fresh-120ml.html" title="Renu Fresh 120ml " tabindex="-1" class="product-item-photo">

                  <span class="product-image-container" style="width:165px;">
            <span class="product-image-wrapper" style="padding-bottom: 100%;">
                <img class="product-image-photo" src="http://.../pub/media/catalog/product/cache/3a98496dd7cb0c8b28c4c254a98f915a/l/2/l2412989.jpg" max-width="165" max-height="165" alt="Renu Fresh 120ml "></span>
                  </span>
                </a>
                <div class="product-item-details">
                  <strong class="product-item-name">
                                                    <a href="http://.../renu-fresh-120ml.html">Renu Fresh 120ml </a>
                                            </strong>
                </div>
              </td>

              <td class="col price" data-th="Preço">

                <span class="price-excluding-tax" data-label="Excl. Impostos">
                            <span class="cart-price">
                                <span class="price">R$24,90</span> </span>

                </span>
              </td>
              <td class="col qty" data-th="Qtd">
                <div class="field qty">
                  <label class="label" for="cart-2218-qty">
                            <span>Qtd</span>
                        </label>
                  <div class="control qty">
                    <input id="cart-2218-qty" class="input-qty" name="cart[2218][qty]" data-cart-item-id="1350" value="1" type="number" size="4" title="Qtd" class="input-text qty" maxlength="12" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty"><!--Alterei aqui-->
                  </div>
                  <div class="qty-changer">
                    <a href="javascript:void(0)" class="qty-inc"><i class="porto-icon-up-dir"></i></a>
                    <a href="javascript:void(0)" class="qty-dec"><i class="porto-icon-down-dir"></i></a>
                  </div>
                </div>
              </td>

				<td class="col subtotal" data-th="Subtotal">
					<span class="price-excluding-tax" data-label="Excl. Impostos">
						<span class="cart-price">
							<span class="price">R$24,90</span>
						</span>

					</span>
				</td>
            </tr>
            <tr class="item-actions">
              <td colspan="100">
                <div class="actions-toolbar">
                  <div id="gift-options-cart-item-2218" data-bind="scope:'giftOptionsCartItem-2218'" class="gift-options-cart-item">
                    <!-- ko template: getTemplate() -->
                    <!-- ko if: isActive() || hasActiveOptions() -->
                    <!-- /ko -->
                    <!-- /ko -->

                  </div>
                  <a class="action action-edit" href="http://.../checkout/cart/configure/id/2218/product_id/64516/" title="Editar parâmetros do item">
                    <span>
                    Editar        </span>
                  </a>
                  <a href="#" title="Remover item" class="action action-delete" data-post="{&quot;action&quot;:&quot;http:\/\/...\/checkout\/cart\/delete\/&quot;,&quot;data&quot;:{&quot;id&quot;:&quot;2218&quot;,&quot;uenc&quot;:&quot;aHR0cDovLzE4LjIyOS4xNDUuODQvY2hlY2tvdXQvY2FydC8,&quot;}}">
                    <span>
                Remover item    </span>
				<button class="updateCar" type="submit" name="update_cart_action" data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;"><span>Atualizar</span></button><!--Fiz a alteração aqui-->
                  </a>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="cart main actions">
        <a class="action continue" href="http://.../" title="Continuar Comprando">
          <span>Continuar Comprando</span>
        </a>
        <button type="submit" name="update_cart_action" data-cart-empty="" value="empty_cart" title="Limpar Carrinho de Compras" class="action clear" id="empty_cart_button">
                    <span>Limpar Carrinho de Compras</span>
                </button>
        <input type="hidden" value="" id="update_cart_action_container" data-cart-item-update="">
      </div>
    </form>
	
	<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
	<script src="main.js"></script>    
</body>
</html>

Then I did the script this way:

function togleButton(event, qtdPadrao){
	let qtdAlterada = event.target.value;
	let index = Array.from(QtdyProducts).indexOf(event.target);
	let buttonUp = document.querySelectorAll('.updateCar');
	if (qtdPadrao == qtdAlterada)
		buttonUp[index].style.display="none"
	else
		buttonUp[index].style.display="";
}

let QtdyProducts = document.querySelectorAll('.input-qty');

QtdyProducts.forEach(function(product){
	let qtdPadrao = product.value;
	product.addEventListener('blur', function(){
		togleButton(event, qtdPadrao);
	}, false);
})

Now some explanations.

The first thing I did was to store all quantity inputs in a variable:

let QtdyProducts = document.querySelectorAll('.input-qty');

Then using the forEach() i pass this variable and for each item I save the default value of the quantity input in a variable, to be able to pass to the function togleButton() beyond the event itself.

It’s important to note that if I hadn’t put the

function(){
   togleButton(event, qtdPadrao);
}, false

in the addEventListener() he would call the function togleButton() as soon as the page loaded and would give error.

Already in office togleButton() i store user changed quantity in a variable:

let qtdAlterada = event.target.value;

To be able to compare with the default quantity that was set for the quantity input.

Then store in a variable the index of the current input user is changing the value:

Array.from(QtdyProducts).indexOf(event.target);

And store also all existing buttons in a variable again:

let buttonUp = document.querySelectorAll('.updateCar');

Finally I compare if the changed quantity equals the standard quantity:

if (qtdPadrao == qtdAlterada)
    buttonUp[index].style.display="none"
else
    buttonUp[index].style.display="";

If it’s the same I change the display to "None", if it’s different I remove the display "None".

  • 1

    oi @Renatogonçales , first of all I thank you for your dedication in the answer. I would also like to share how this problem was solved, with the help of a co-worker. See the solution taken.

0


function habilitaButton(numero) {
		var qtd = document.getElementsByClassName("input-text qty");
		var btn = document.getElementsByClassName("qty-changer");
		var num = 0;
		for(var x = 0; x < qtd.length; x++){
			if(qtd[x] == numero){
				num = x;
			}
		}
		for(var y = 0; y < btn.length; y++){
			if(btn[y] == numero){
				num = y;
			}
		}

		document.getElementsByClassName("action update")[num].style.display = "block";
	  }
	var QtdyProduct = document.getElementsByClassName("control qty");
	var divTableCart = document.getElementById('shopping-cart-table');
	var itemProduct = divTableCart.getElementsByClassName('action-delete');
	document.getElementsByName("update_cart_action")[1].style.display = "none";
	for(var j =0; j < itemProduct.length; j++){	
		itemProduct[j].insertAdjacentHTML("afterend", '<button type="submit" name="update_cart_action" style="display:none;" data-cart-item-update="" value="update_qty" title="Atualizar" class="action update"><span>Atualizar</span></button>');
	}  
	for(var i =0; i < QtdyProduct.length; i++){	
		var qtdAlterada = QtdyProduct[i].getElementsByTagName('input')[0];
		document.getElementsByClassName("qty-changer")[i].onclick = function(){
			habilitaButton(this);
		}
		qtdAlterada.onchange = function(){
			habilitaButton(this);
		}
	}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.