Help with jQuery. on calculation of plots!

Asked

Viewed 765 times

6

inserir a descrição da imagem aqui

Guys, I have a slightly complicated question for myself that I’m a beginner.. I’m developing a system where the user can select the amount of installments they want to split their purchase.. until then ok.. however a field has been requested where the user can enter the amount he can pay per installment.. and when filling automatically it must identify which value divided by 12 comes closer to the value filled. I have the following code so far...

    $(document).ready(function () {

        // Aqui ele pega o valor do campo "Você pode pagar.." -> aqui que preciso de ajuda!
        $('#parcelaAprox').change(function() {
            console.log($('#parcelaAprox').val());

            console.log($('#PrecoManager').val().replace(',', '.') / 12);

            $.each(test, function (index, item) {
                console.log(index);
            });

        });

        // Aqui ao carregar a página como padrão o valor de parcelas é 12
        var vParcela = $('#PrecoManager').val().replace(',', '.') / $('#nParcelas').val();
        vParcela = parseFloat(vParcela).toFixed(2).replace('.', ',');
        $('#vParcela').html(vParcela);

        // Aqui ele divide o valor do produto pela quantidade de parcelas selecionadas
        $('#nParcelas').change(function () {
            var vParcela = $('#PrecoManager').val().replace(',', '.') / $('#nParcelas').val();
            vParcela = parseFloat(vParcela).toFixed(2).replace('.', ',');
            $('#vParcela').html(vParcela);
        });

    });

Thank you!

  • I didn’t understand your doubt!

2 answers

5

$(document).ready(function() {
  var total = 600; // valor base do produto
  $('#valor, #nParcelas').on('change input', function(e) {
    var valor = Number($('#valor').val().replace(/\./g, '').replace(',', '.') || 0);
    var parcelas = Number($('#nParcelas').val());

    if (this.id == 'valor') { // caso de mudar o valor
      var match = {diff: Infinity};
      for (var i = 1; i <= 12; i++) {
        var diferenca = Math.abs(total - valor * i);
        if (diferenca < match.diff) match = {i: i, diff: diferenca};
      }

      $('#nParcelas').val(parcelas = match.i);
      if (parcelas * valor < total) return $('#vParcela').text('O valor é demasiado baixo...');
    }

    $('#valor').val((valor = (total / parcelas)));
    $('#vParcela').text('R$ ' + (total / parcelas).toLocaleString('pt-br'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Total: R$600</p>
<input id="valor" />
<select id="nParcelas" value="12">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
  <option>7</option>
  <option>8</option>
  <option>9</option>
  <option>10</option>
  <option>11</option>
  <option selected>12</option>
</select>
<select id="vVencimento">
  <option value="1">Dia 1</option>
  <option value="2">Dia 2</option>
  <option value="3">Dia 3</option>
  <option value="4">Dia 4</option>
  <option value="5">Dia 5</option>
  <option value="6">Dia 6</option>
  <option value="7">Dia 7</option>
  <option value="8">Dia 8</option>
  <option value="9">Dia 9</option>
  <option value="10" selected>Dia 10</option>
</select>
<span id="vParcela"></span>

4


I made an example based on your fields of how you should behave.

I basically used two variables to compare the entered value and store the lowest occurrence between the plots. I also added an Array to store the plots and facilitate comparison.

$(document).ready(function(){
  // Valor do produto para teste
	let ValorTotal = 5000.00;
  
    let eParcelas = $("#qtdParcelas");
    let parcelas = [];
  
  for(let i = 1; i <= 12; i++) {
  	let option = $('<option>');
    let valorParcela = ValorTotal/i
  	eParcelas.append(option.attr('value', i).append(`${i}x Parcelas de R$ ${valorParcela.toLocaleString()}`));
    
    // Pra facilitar a comparação eu jogo as parcelas em um array;
    parcelas.push({
    	qtdParcelas: i,
        valor: valorParcela
    });
  }
  
  $('#possoPagar').keyup(function(e){
  	let valor = $('#possoPagar').val();
    let valorIdeal = 0;
    parcelas.forEach(function(v, i){
    	if(v.valor <= valor && v.valor >= valorIdeal) {
      	valorIdeal = v.valor;
      	$("#valorIdeal").html(`${v.qtdParcelas}x de R$ ${v.valor}`);
               
        eParcelas.val(v.qtdParcelas);
      }
    });
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <div>
    <label>Quanto você pode pagar?</label>
    <input type="number" name="possoPagar" id="possoPagar" />
  </div>
  <div>
    <label>Parcelas</label>
    <select name="qtdParcelas" value id="qtdParcelas">      
    </select>
  </div>
  
  <h3>
    Valor ideal da parcela
  </h3>
  <div id="valorIdeal">
  </div>
</form>

Just adapt the logic to your need, hope to have helped.

  • Nice guy, I think it’ll help. I will analyze your code here and try to adapt to my hope that it works as soon as you have any result I return you. Thank you!

  • @Ok Drik, any doubt post in the comments I have assist you as soon as possible. Good luck :)

  • Man, cool helped me.. I was able to adapt to my code but I believe that in the if part is necessary some adjustment, for example.. I have a product of 1599,00 if I type 500 it goes to the option of 4x 400 more should go to 3x of 533, because it is the value that comes closer to 500 correct? I’m trying to improve here more if you can give me some hint would be good.. Thanks again very much! (y)

  • Make a range, sum 10% of the value typed to give the margin. For example. 500 - 550, 300 - 330, 200 - 220, 290 - 319. So Victor can get closer.

  • I didn’t really understand the logic.. = x

  • The problem is that while it is less than the value of the plot it does not recognize that plot

Show 1 more comment

Browser other questions tagged

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