List and sum selected items

Asked

Viewed 641 times

0

I need to list the value in (R$) inputs and select html, as if it were a shopping cart, but I need this list and total value to be presented in real time to the user to be sent the list by email... Could someone help me?

h3 {
  font-size: 18px;
  border-left: 2px solid #cf529e;
  padding-left: 10px;
}

label {
  font-size: 13px;
}

textarea {
  width: 100%;
  padding: 10px;
  border-radius: 5px;
  margin-bottom: 10px;
}

.form-check-label {
  margin-right: 50px;
}

.opcionais {
  padding: 20px 0;
}

.selecionados {
  background-color: #fcfcfc;
  border: 1px solid #848484;
  padding: 20px;
  border-radius: 5px;
  margin-top: 45px;
}
<div class="container">
  <div class="row" id="festa">
    <div class="col-md-5 col-md-offset-1">
      <form>
        <h3>Dados Pessoais</h3>
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Nome Completo*">
        </div>
        <div class="form-group">
          <input type="email" class="form-control" placeholder="Email Válido*">
        </div>
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Telefone">
        </div>
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Como ficou sabendo sobre festas?">
        </div>
        <hr>

        <h3>Monte a sua Festa</h3>
        <div class="form-group">
          <label>Escolha uma unidade</label>
          <select class="form-control">
            <option>-</option>
            <option value="200">1 Shopping</option>
            <option value="200">2 Shopping</option>
            <option value="100">3 Shopping</option>
            <option value="100">4 Plaza</option>
            <option value="100">5 Shopping</option>
            <option value="100">6 Plaza</option>
          </select>
        </div>

        <div class="form-group">
          <input type="date" class="form-control">
        </div>
        <div class="form-group">
          <input type="checkbox" value="1499" /> <label class="form-check-label">Festa K</label>
          <input type="checkbox" value="2000" /> <label class="form-check-label">Festa S</label>
        </div>
        <hr>

        <h3>Itens Opcionais</h3>
        <div class="row">
          <div class="opcionais">
            <div class="col-md-3">
              <div class="form-group">
                <label> <input type="checkbox" value="1000"> Buffet</label>
                <label> <input type="checkbox" value="499"> Decoração</label>
                <label> <input type="checkbox" value="800"> Foto</label>
              </div>
            </div>
            <div class="col-md-4">
              <label> <input type="checkbox" value="100"> Vídeo</label>
              <label> <input type="checkbox" value="300"> Personagens</label>
              <label> <input type="checkbox" value="150"> Convites</label>
            </div>
          </div>
        </div>

        <h3>Finalizar Orçamento</h3>
        <div class="finaliza">
          <textarea name="address" placeholder="Deseja acrescentar algo?"></textarea>
        </div>

        <input type="submit" name="submit" class="submit action-button" value="Finalizar" />
      </form>
    </div>
    <div class="col-md-3 col-md-offset-2">
      <div class="selecionados">
        Itens Selecionados

        <div class="total">Total: <span>R$ 0,00</span></div>
      </div>
    </div>
  </div>
</div>

  • What you want is to show a list of everything that was selected for the user, is this?

  • That’s right, but showing the value of each item, as if it were a shopping cart

2 answers

3

There are n ways to do what you want, follow an example of one of them, I don’t know if it’s the best way for your case, but I believe it will give you a basis on how to accomplish exactly what you need.

var objCarrinho = []
var Total = 0

renderCar()

$('li button').on('click', function(){
  var title = $(this).attr('data-name')
  var valor = $(this).attr('data-valor')
  
  objCarrinho = []
  objCarrinho.push({nome: title, valor})
  
  renderCar()
})

function renderCar(){
  objCarrinho.map(function(item){
    let content = `<li>${item.nome} - R$ ${item.valor}</li>`
    
    $('#carrinho').append(content)
    
    Total = parseFloat(Total) + parseFloat(item.valor)
    
    $('#total').text(Total)
  })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Produtos</h1>
  <ul>
    <li>
      iPhone X R$ 6000
      <button data-name="iphone" data-valor="6000">Adicionar ao Carrinho</button>
    </li>
    
    <li>
      Xbox One - R$ 2000
      <button data-name="Xbox One" data-valor="2000">Adicionar ao Carrinho</button>
    </li>
    
    <li>
      Macbook Pro - R$ 12000
      <button data-name="Macbook Pro" data-valor="12000">Adicionar ao Carrinho</button>
    </li>
  </ul>
  
  <h1>Carrinho</h1>
  
  <ul id="carrinho"></ul>
  <span>Total: R$ <strong id="total">0</total></span>

  • You’ve given me so much help, I just need to adapt to what I need right now, thank you.

  • @Jvscorrêa Legal, could mark the answer as solved?

0


Good first of all, it would be interesting for you to define if you are using any Javascript framework for this type of question so that we can answer you properly. As not defined I believe you are using jQuery for such... I made the template in pure javascript so you can change it if you want.

In theory, what you need is a function to capture the data of all these elements, and based on this make the final calculation and then use it as needed, either to save or show the user, so:

(function(){

    var ids = ['list-lugar', 'add-festa-k', 'add-festa-s', 'add-buffet',
               'add-decoracao', 'add-foto', 'add-video', 'add-personagens', 
               'add-convites'];

    // retorna um elemento usando seu seletor (aka jQuery)
    function getEl(id) {
        try {
            return document.getElementById(id);
        } catch(ex) {
            return null;
        }
    }

    // captura o valor do elemento (independente do tipo)
    function getValue(id) {
        try {
            var el = getEl(id), value = 0;
            switch(el.nodeName.toLowerCase()) {
                case 'select': 
                    value = parseFloat(el.options[el.selectedIndex].value);
                    break;
                case 'input' : 
                    switch(el.type) {
                        case 'checkbox': 
                            value = !!el.checked ? parseFloat(el.value): 0;
                            break;
                        // caso haja mais de um tipo de input, entra aqui...
                    }
                    break;
                // caso haja mais algum tipo de elemento, entra aqui...
            }
            return value;
        }
        catch(ex) {
            return 0;
        }
    }

    // faz o cálculo real e retorna
    function calc() { 
        try {

            var value = 0;

            for(var id of ids) value += getValue(id);

            return value;

        } catch(ex) {
            return 0;
        }
    }

    // mostra ao usuario
    function show(valor){
        document.getElementById('result')
                .innerHTML = "R$ " + valor.toString().replace('.',',');
    }

    // init main
    for(var id of ids)
        getEl(id).addEventListener('change', function(){ show(calc()) }, false);

    show(calc());

})();
<div>
    <label for=""></label>
    <select class="form-control" id="list-lugar">
        <option value="0" disabled="true" selected="true">-</option>
        <option value="200">1 Shopping</option>
        <option value="200">2 Shopping</option>
        <option value="100">3 Shopping</option>
        <option value="100">4 Plaza</option>
        <option value="100">5 Shopping</option>
        <option value="100">6 Plaza</option>
    </select>
</div>
<div>
    <input id="add-festa-k" type="checkbox" value="1499" />
    <label>Festa K</label>
    <input id="add-festa-s" type="checkbox" value="2000" />
    <label>Festa S</label>
</div>
<div>
    <input id="add-buffet" type="checkbox" value="1000" />
    <label>Buffet</label>
    <input id="add-decoracao" type="checkbox" value="499" />
    <label>Decoração</label>
    <input id="add-foto" type="checkbox" value="800" />
    <label>Foto</label>
    <input id="add-video" type="checkbox" value="100" />
    <label>Vídeo</label>
    <input id="add-personagens" type="checkbox" value="300" />
    <label>Personagens</label>
    <input id="add-convites" type="checkbox" value="150" />
    <label>Convites</label>
</div>
<h1 id="result"></h1>

Note: I advise to refactor your HTML code because its structure is not in accordance with HTML5 metrics. It is not placed input inside label but it’s just a piece of advice...

Note 2: another detail, I advise you to start studying about more robust frameworks like the React, Angular, Vuejs if you are going to make treatments like these because they improve the structure of the code and prevent some "smart guy" to access your form by inspection and change the final values... I say this because by the logic of your solution I could have a party with all the options for free, just changing the "values" to 0...

  • 1

    Thank you very much Leandro, I will follow your recommendations, I started to study Angularjs, that would be exactly what I needed I will reinforce these points that you advised me!

  • For you who are starting now, take a look at Vuejs first... he is "less" complicated to understand in the beginning... it took me 6 months to understand Angularjs. Today seems child’s play rsrs

  • To list the value of each checkbox or combobox selected before the total sum works in the same way as the example?

  • yes, the Calc function is taking all the elements that are listed in the var ids=[...] that is, if you want to do another calculation you just need to make your Loop picking one by one. I just created the arrayl ids to make it easy

Browser other questions tagged

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