javascript - Create multiple lines with pre-programmed add buttons

Asked

Viewed 60 times

0

Hey, guys. What’s up? I just started studying Javascript and, to train, I figured out a simple exercise: A screen, where there is the "Add Product" button that adds a row in the table below. It’s kind of like an e-commerce shopping cart. My question is this: When adding a line, I wanted the "+" button to add a unit in the amount and the "-" to take out. The problem is that for the first item, I even managed to program, but for those that will be generated after "Add Product" I could not at all. I cleaned up the code, because because of the various tests I had done, it was a mess. Then, I really wanted this help. How can I make the add and remove buttons to be created already programmed to mess with the amount of your line?

// Write JavaScript here 
window.onload = function() {
    tableEl = document.getElementById('tabelaDados');
    btnAddLine = document.getElementById('btnAddLine');
    

    btnAddLine.addEventListener('click', function(){
        var tr = document.createElement('tr');
    
        tr.innerHTML = 
            `
                <td><button>-</button> 1  <button>+</button> </td>
                <td>carro</td>
                <td>R$ 55.000,00</td>
                <td>R$ 55.000,00</td>    
            `
    
        tableEl.appendChild(tr);
    });
}
#tabelaHeader {
    height: 50px;
    width: 600px;
}

#tabelaDados {
    position: relative;
    height: 50;
    width: 600px;
    left: 60px;
}
<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Usuários - Teste </title>
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <link rel="stylesheet" type="text/css" href="../css/estilo.css">
    </head>

    <body>
        <div class="menu">
            <button id="btnAddLine">Adicionar Produto</button>
        </div>
        <table id="tabelaHeader">
            <thead>
                <tr>
                    <th>Quantidade</th>
                    <th>Descrição</th>
                    <th>Valor Unitário</th>
                    <th>Valor Final</th>
                </tr> 
            </thead>
        </table>

        <table id="tabelaDados">
            <thead>
                <tr>
                    <td><button>-</button>1  <button>+</button> </td>
                    <td>carro</td>
                    <td>R$ 55.000,00</td>
                    <td>R$ 55.000,00</td>  
                </tr>
            </thead>
        </table>
    

If you could take a look to help me, I’d appreciate it!

1 answer

0


What happens is that when Voce adds the new line with the buttons + and -, your code does not know about this new element, so it works only on the first line that is already in HTML.

The idea would be to add the Istener to the buttons + and - every time you add a new line.

With this jquery and very simple, I think you can understand the general idea.

$(window).ready(function(){
    var $tableEl = $('#tabelaDados');
    var btnAddLine = $('#btnAddLine');

    btnAddLine.on('click',function(){
        var tr = document.createElement('tr');
    
        tr.innerHTML = 
            `
                <td>
                  <button class="sub">-</button>
                  <span class="qtd">1</span>
                  <button class="add">+</button>
                </td>
                <td>carro</td>
                <td>R$ 55.000,00</td>
                <td>R$ 55.000,00</td>    
            `
    
        $tableEl.append(tr);
    });
    
    //aqui e a grande magica, de um jeito simples ele monitora o elemento #tabelaDados
    //e aplica o listener de click sempre que um novo elemento com a classe .add aparece
    
    //Na verdade o termo correto para voce estudar é eventPropagation/eventBubbling
    $('#tabelaDados').on('click', '.add', function(){
      var $tr = $(this).parent().parent()
      var $qtd = $tr.find('.qtd')
      $qtd.text(parseInt($qtd.text())+1)
    })
    
    $('#tabelaDados').on('click', '.sub', function(){
      var $tr = $(this).parent().parent()
      var $qtd = $tr.find('.qtd')
      var qtdInt = parseInt($qtd.text())
      if(qtdInt>0){
        $qtd.text(qtdInt-1)
      }
    })
})
#tabelaHeader {
    height: 50px;
    width: 600px;
}

#tabelaDados {
    position: relative;
    height: 50;
    width: 600px;
    left: 60px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Usuários - Teste </title>
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <link rel="stylesheet" type="text/css" href="../css/estilo.css">
    </head>

    <body>
        <div class="menu">
            <button id="btnAddLine">Adicionar Produto</button>
        </div>
        <table id="tabelaHeader">
            <thead>
                <tr>
                    <th>Quantidade</th>
                    <th>Descrição</th>
                    <th>Valor Unitário</th>
                    <th>Valor Final</th>
                </tr> 
            </thead>
        </table>

        <table id="tabelaDados">
            <thead>
            </thead>
        </table>

  • thank you so much for your help! It was extremely simple, as you said yourself. Can you just explain something to me, just so I understand? No jQuery, lines: var $tr = $(this). Parent(). Parent() var $Qtd = $tr.find('.Qtd') $Qtd.text(parseint($Qtd.text())+1) What it does is: - Pick up the 'tr' that parent (which is in innerHTML) - search for the span Qtd - apply the addition of the quantity The idea is this then, right? the "this" that is in the $tr variable refers to the #tableDados? Thank you again, Neuber! :)

  • this do tr is pointing to the clicked element, . sub and .add. As for Parent(). Parent() and that’s right, I go to tr and Partit dai and look for Qtd, in fact only needed a Parent(). I’m not going to say it’s the right way, it’s just how I do it, because depending on how you change the structure of HTML you’ll need to change the js,.....

  • Perfect, Neuber! Thank you so much for your help, explanation and patience, really! :)

  • if the answer helped you choose it as the best, so Voce also contributes to the site ^^

Browser other questions tagged

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