Add button does not differentiate products

Asked

Viewed 50 times

0

I’m a beginner in HTML and Javascript and I’m caught in a problem for a college project. Basically I have an e-commerce without BD, so the products are defined in HTML.

My problem is that by clicking the add button to the cart, it does not differentiate the products and ends up adding only the first product.

<div class="container-fluid">
    <!-- Essa class row que é a linha que eu falei-->  
    <div class="row"> 
        <div class="col-md-3 col-xs-3" id="Fonte">
            <fieldset>
            <legend class="prod">Fonte Corsair 400w</legend>
                 <img src="imagens/Fonte/fonte-corsair-vs400-80plus-white-pfc-ativo-400w-cp-9020117-la-1502453690.jpg" id="foto">
            <p>R$: </p><p input type="number" id="txtValor">229.90</p>
            <p>
                Quantidade<br>
                <input type="number" id="txtQtde" min="1" max="5" oninput="calcTotal();">
            </p>
            <button type="add" class="btn btn-primary btGravar">
                Adicionar
               <i class="fas fa-plus"></i>
            </button> 
        </fieldset>
    </div> 
    <div class="col-md-3 col-xs-3" id="pv1060">
        <fieldset>
            <legend class="prod">GTX 1060 3GB</legend>
                 <img src="imagens/Placa_de_video/placa-de-video-geforce-galax-gtx-1060-oc-3gb-60nnh7dsl9c3-gddr5-pci-exp_33631.jpg" id="foto">
            <p id="txtValor">
               R$ 1349,90
            </p>
            <p>
                Quantidade<br>
                <input type="number" id="txtQtde" min="1" max="5" oninput="calcTotal();">
            </p>
            <button type="add" class="btn btn-primary btGravar">
                Adicionar
               <i class="fas fa-plus"></i>
            </button> 
        </fieldset>
    </div>
    </section>

Javascript

$(".btGravar").on('click', function(){
    var produto = $('.prod').html();
    var quantidade = document.getElementById("txtQtde").value;
    var orçamento = $('#txtValor').html();
    var valor = orçamento * quantidade;
    var adicionar = '<tr><td>' + produto + '</td><td>' + quantidade +'</td><td>' + valor + '</td><td><button class="btn btn-danger btApagar"><span class="glyphicon glyphicon-trash"></span>Apagar</button></td></tr>';
    $(".tb0").prepend(adicionar);
    $("#shopCart").modal("show");
    }
)
  • You have two classes with the same name

  • Managed to solve?

3 answers

1

Dude, I made an example for you, so I’m gonna summarize everything you need to research and think about first. Take a look at the documentation that you will understand everything that has been done.

In HTML:

  • Do not use ID’s for more than one element, if you will have two elements with the same ID this should be a CLASS
  • Pay attention to tag closure or incorrect structure, you have a

    and one merged, may be giving some conflict.

  • So, all that was duplicate ID I used Classes.

In Javascript:

  • In Javascript, especially in Click Handlers, you have a variable this, this variable will indicate which element held that particular event. In the case of the button, it will be the button element.
  • By this element you can find the other elements, through methods such as .closest() and .find().
  • In my example, I used the button to find the parent div that has the product ID, and from that div I was able to find the internal elements that contain the values, name and input.

$(".btGravar").on('click', function() {
  var botaoClicado = $(this);
  var produtoClicado = botaoClicado.closest('div');

  var produto = produtoClicado.find('.prod').html();
  var quantidade = produtoClicado.find('.txtQtde').val();
  var orcamento = produtoClicado.find(".txtValor").html();
  var valor = orcamento * quantidade;
  console.log(produto, quantidade, orcamento, valor);
  //     var adicionar = '<tr><td>' + produto + '</td><td>' + quantidade +'</td><td>' + valor + '</td><td><button class="btn btn-danger btApagar"><span class="glyphicon glyphicon-trash"></span>Apagar</button></td></tr>';
  //     $(".tb0").prepend(adicionar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-3 col-xs-3" id="Fonte">
    <fieldset>
      <legend class="prod">Fonte Corsair 400w</legend>
      <img src="imagens/Fonte/fonte-corsair-vs400-80plus-white-pfc-ativo-400w-cp-9020117-la-1502453690.jpg" id="foto">
      <p>R$:
        <span class="txtValor">229.90</span>
        <p>
          Quantidade
          <br>
          <input type="number" class="txtQtde" min="1" max="5">
        </p>
        <button type="add" class="btn btn-primary btGravar">
                            Adicionar
                            <i class="fas fa-plus"></i>
                        </button>
    </fieldset>
  </div>
  <div class="col-md-3 col-xs-3" id="pv1060">
    <fieldset>
      <legend class="prod">GTX 1060 3GB</legend>
      <img src="imagens/Placa_de_video/placa-de-video-geforce-galax-gtx-1060-oc-3gb-60nnh7dsl9c3-gddr5-pci-exp_33631.jpg" id="foto">
      <p>
        R$
        <span class="txtValor">1349.90</p>
                    </p>
                    <p>
                        Quantidade
                        <br>
                        <input type="number" class="txtQtde" min="1" max="5">
                    </p>
                    <button type="add" class="btn btn-primary btGravar">
                        Adicionar
                        <i class="fas fa-plus"></i>
                    </button>
                </fieldset>
            </div>

1

You have duplicated Id’s, there can be no id’s with the same name referencing different elements, so you should use class. The code you are doing understands that it should fetch an id (which should only have 1 with that name), so it only returns 1 product, it finds the first id with the name you passed and already returns.

0

As they said in the other answers, don’t use the same id in several elements. Exchange the:

id="txtValor" and id="txtQtde"

for

class="txtValor" and class="txtQtde"

In the script you will get these values with:

var quantidade = $(this).closest("fieldset").find(".txtQtde").val();
var orçamento = $(this).closest("fieldset").find(".txtValor").html();

Another problem is getting the price in the variable orçamento. As you are taking the HTML of the element, the return will come something like R$ 229,90, which is not a valid number to make calculations.

By the way, you’re using two different constructions:

<p>R$: </p><p input type="number" id="txtValor">229.90</p>

and

<p id="txtValor">
   R$ 1349,90
</p>

I suggest you leave in the form of the second, even because the first is invalid. Leave it like this:

<p id="txtValor">
   R$ 1349,90
</p>

To get the price in valid numerical form (only the numbers of R$ 1349,90), you use a regular expression with .match():

orçamento = orçamento.match(/[\d|\,]+/)[0].replace(",", ".");

A regex /[\d|\,]+/ will take only numbers and comma, resulting in 1349,90, but it is also necessary to replace the comma by point to delimit the decimal places, since Javascript considers only the point as decimal delimiter, so the .replace(",", ".").

Once this is done, your code (at least as shown in the question) will be functional:

function calcTotal(){
}

$(".btGravar").on('click', function(){
    var produto = $('.prod').html();
    var quantidade = $(this).closest("fieldset").find(".txtQtde").val();
    var orçamento = $(this).closest("fieldset").find(".txtValor").html();
    orçamento = orçamento.match(/[\d|\,]+/)[0].replace(",", ".");
    console.log(orçamento);
    var valor = orçamento * quantidade;
    var adicionar = '<tr><td>' + produto + '</td><td>' + quantidade +'</td><td>' + valor + '</td><td><button class="btn btn-danger btApagar"><span class="glyphicon glyphicon-trash"></span>Apagar</button></td></tr>';
    $(".tb0").prepend(adicionar);
    $("#shopCart").modal("show");
    }
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

<table class="tb0"></table>
<div class="container-fluid">
    <!-- Essa class row que é a linha que eu falei-->  
    <div class="row"> 
        <div class="col-md-3 col-xs-3" id="Fonte">
            <fieldset>
            <legend class="prod">Fonte Corsair 400w</legend>
                 <img src="imagens/Fonte/fonte-corsair-vs400-80plus-white-pfc-ativo-400w-cp-9020117-la-1502453690.jpg" id="foto">
            <p class="txtValor">R$: 229,90</p>
            <p>
                Quantidade<br>
                <input type="number" class="txtQtde" min="1" max="5" oninput="calcTotal();">
            </p>
            <button type="add" class="btn btn-primary btGravar">
                Adicionar
               <i class="fas fa-plus"></i>
            </button> 
        </fieldset>
    </div> 
    <div class="col-md-3 col-xs-3" id="pv1060">
        <fieldset>
            <legend class="prod">GTX 1060 3GB</legend>
                 <img src="imagens/Placa_de_video/placa-de-video-geforce-galax-gtx-1060-oc-3gb-60nnh7dsl9c3-gddr5-pci-exp_33631.jpg" id="foto">
            <p class="txtValor">
               R$ 1349,90
            </p>
            <p>
                Quantidade<br>
                <input type="number" class="txtQtde" min="1" max="5" oninput="calcTotal();">
            </p>
            <button type="add" class="btn btn-primary btGravar">
                Adicionar
               <i class="fas fa-plus"></i>
            </button> 
        </fieldset>
    </div>
    </section>
</div>

Browser other questions tagged

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