How to capture the unique element in HTML?

Asked

Viewed 67 times

0

My doubt is a little confusing, but I hope to be as clear as possible. As shown in the image ( https://i.stack.Imgur.com/Lafjw.png ) I have a cart and the div of each element (product) has the same id, since it is the model and all other products will use the same structure. The problem is that when I add an item in the first product (rice) all products suffer the addition, since they use the same ID, and in javascript the command happens using the ID. Would it be possible to generate a different ID every time a new product is added to the cart? As if it were the primary key of a database.

HTML of one of the cart items:

<div class="container-fluid" id="modeloProdutos">
                    <div class="row">
                        <!-- descrição produtos + imagem -->
                        <div class="col-sm-12 col-md-4 col-lg-6">
                            <img src="img/arroz.jpg">
                            Arroz integral tipo C 5KG Arroz integral tipo C 5KG Arroz integral tipo C 5KG Arroz integral tipo C 
                        </div>

                        <div class="col-sm-12 col-md-4 col-lg-2">
                            <!-- informar quantidade de produtos -->
                            <div class="container-fluid" id="divAddProdutosPagamentos">
                                <div class="row">
                                    <!-- Botão de subtrair -->
                                    <!-- nao consigo redimensionar o botao -->
                                    <div class="input-group-prepend col-lg-3" id="buttonMinus">
                                        <button class="btn btn-primary" type="button"><i class="fas fa-minus"></i></button>
                                    </div>
                                    <!-- Campo p/ informar a qtd-->
                                    <!-- aqui vai setado a quantidade de itens informado no index -->
                                    <input type="text" class="form-control input-group-prepend col-lg-3" id="inputQtd" 
                                    value="0">

                                    <!-- Botão de adicionar -->
                                    <div class="input-group-prepend col-lg-3" id="buttonAdd">
                                        <button class="btn btn-primary" type="button"><i class="fas fa-plus"></i></button>
                                    </div>
                                </div>
                            </div> <!-- FIM DA DIV ADD PRODUTO -->
                        </div>

                        <div class="col-sm-12 col-md-4 col-lg-2">
                            R$ 23.11
                        </div>

                        <div class="col-sm-12 col-md-4 col-lg-2">
                            R$ 43.44 
                        </div>

                    </div>
                </div>

Javascript:

    $(document).ready(function(){
  $('#buttonAdd').click (function(){
    count++
    $('#inputQtd').val(count);
    $('#badgeCarrinho').text(count);
  });
});

PS: badgeCart is a notification next to the cart icon in the upper right corner (where 4)

  • The same id is not used for more than one element. An id must be unique. Use class instead of id.

  • 1

    It wouldn’t have the same effect this.

  • I understood what I meant, I believed that this worked for the ID too, forgive my ignorance.

1 answer

2


How to capture the unique element in HTML?

An id should be unique on a page. This error is very common around here because people do not know its use well. The attribute name itself indicates that it must be unique: id is an identity of something, so the term "identity" indicates that something that possesses that identity only it possesses. It would be like a number of CPF or even RG, where each citizen has his. Imagine two or more people have the same CPF, what confusion would not give!

Already the class (attribute class) one or more elements may have the same. Making an analogy, one or more people may be bald, that would be the class, but the identity of each is different:

João: é careca e possui o CPF 1234
Pedro: é careca e possui o CPF 4567

Seria:

John and Peter have the "bald" class, but each has its own unique CPF.

In the case of Javascript, you can take the element by class using the this. The this inside the event represents the element that triggered the event. In your case, you would have to change the #buttonAdd by a class .buttonAdd:

<div class="input-group-prepend col-lg-3" class="buttonAdd">

And the same for quantity input, changing id="inputQtd" for class="inputQtd":

<input type="text" class="form-control input-group-prepend col-lg-3" class="inputQtd" 
                                value="0">

And in jQuery change the selector to class and search inside the div .row (the add button and quantity input are within the same div .row) the element that has the class .inputQtd using .closest() and .find() for:

$('.buttonAdd').click(function(){
   count++
   $(this).closest('.row').find('.inputQtd').val(count);
   $('#badgeCarrinho').text(count);
});

Likewise, change the id="divAddProdutosPagamentos" for class: class="divAddProdutosPagamentos", where you can use .closest() to find the quantity input:

$('.buttonAdd').click(function(){
   count++
   $(this).closest('.divAddProdutosPagamentos').find('.inputQtd').val(count);
   $('#badgeCarrinho').text(count);
});

If you independently increment each quantity, do not use the variable count for these inputs. You will do so by taking the value of the input and adding +1:

$('.buttonAdd').click(function(){

   var iqtd = $(this).closest('.divAddProdutosPagamentos').find('.inputQtd');
   var qtd = Number(iqtd.val());

   iqtd.val(qtd+1);
   $('#badgeCarrinho').text(count);
});
  • Whatever before or after.

  • Man... it worked. I didn’t know the functions of Closest, find and everything, so I’ll have to study this code to see how it works. In the case of this example, Voce used the class 'Row' because the elements you used were inside it?

  • 1

    Yes. Closest() searches for the nearest parent element where the elements are inside. find() searches for any child element that is inside. It’s quite simple.

  • I understand... not to abuse your good will, but could you help me with one more question? My Count continues to be used by all fields, for example: in the first field it was worth 4, so in the second field it continues from there (5, 6 and 7). Would I make it unique too?

  • 1

    Yes. In this case you wouldn’t have to use the Count variable. Forget it. Vc increments the amount by searching the field value . inputQtd and sum +1.

  • I added in the answer. See if that’s what you wanted.

  • 1

    You saved me from many a morning of insomnia, thank you very much!

  • I’m happy to help. Tmj!

Show 3 more comments

Browser other questions tagged

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