Add button does not differentiate products

0

I'm a beginner in HTML and JavaScript and I'm stuck in trouble 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 to cart button, it does not differentiate 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");
    }
)
    
asked by anonymous 18.06.2018 / 18:31

3 answers

1

You have duplicate Id's, there can not be id's with the same name referencing different elements, for this you should use class. The code that 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 it already returns.

    
18.06.2018 / 19:02
1

Dude, I've set an example for you, I'll summarize everything you need to research and think about first. Take a look at the documentation you will understand everything that has been done.

No HTML:

  • Do not use ID's for more than one element, if you are going to have two elements with the same ID this should be a CLASS
  • Pay attention to the closing tags or incorrect structure, you have a

    and a fused, it may be giving some conflict.

  • So, whatever was duplicate ID I used Classes.

In JavaScript:

  • In JavaScript, especially in Click Handlers, you have a variable this , this variable will indicate the element that performed that particular event. In the case of the button, it will be the button element.
  • For this element you can find the remaining elements, using 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 inner 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><divclass="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>
    
18.06.2018 / 18:58
0

As you said in the other answers, do not use the same id in several elements. Change the:

id="txtValor" and id="txtQtde"

by

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 to get the price in the orçamento variable. Since you are getting the HTML of the element, the return will come something like R$ 229,90 , which is not a valid number to do calculations.

  

By the way, you're using two different constructs:

<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 everything like this:

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

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

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

Regex /[\d|\,]+/ will only take numbers and the comma, resulting in 1349,90 , but you also need to replace the comma by point to delimit the decimal places, since JavaScript only considers the decimal delimiter point , so the .replace(",", ".") .

Once this is done, your code (at least the one 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><scriptsrc="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>
    
18.06.2018 / 19:46