Doubt manipulation of values js

Asked

Viewed 35 times

1

I have the following entries in html:

COD_01     VALOR_01
COD_02     VALOR_02
e asim por diante até....
COD_99     VALOR_99

User will feed each COD and VALUE.

I need to create a js to:

1- Somar todos os Valores, por COD.
2- Preciso exibir um alerta caso a soma de algum código ultrapasse de 1000

Example:

COD_01       VALOR_01
201           200,00
COD_02       VALOR_02
202           100,00
COD_03       VALOR_03
201           900,00

As the value of code 201 has passed 1000, then display message:

Atenção! O valor do código 201 passou de R$ 1000,00

Can make use of jquery, no problem.

  • Put what you have tried and what really your doubt, the homework should be initiated by you

  • Marcus, as I do not use javascript but database, if no one answers me what I will do is the following: an ajax in the event of change in each value input entering in a table of the database and there I handle whatever you need. However I do not want to do this because it is a bazooka to kill an ant. Now, in javascript nothing really came out. I don’t even know what to google.

1 answer

1


The idea is to create an object and go adding the codes that do not exist and adding the values. When an existing code in the object exceeds 1000, displays the alert:

var codigos = {};

var cods = $("input[name*='cod_']");
var vals = $("input[name*='valor_']");

cods.on("blur", function(){
   var cod = $(this).val();
   if(codigos[cod] == null && cod){
      codigos[cod] = 0;
   }
});

vals.on("blur", function(){
   var val = $(this).val();
   if(val){
      var cod_val = $(this).prev("input[name*='cod_']").val();
      var valor = parseFloat(val.replace(".", "").replace(',','.'));
   
      if(codigos[cod_val] + valor > 1000){
         alert("Atenção! O valor do código "+cod_val+" passou de R$ 1000,00");
      }else{
         codigos[cod_val] += valor;
      }
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="código" type="text" name="cod_01" />
<input placeholder="valor" type="text" name="valor_01" />
<br />
<input placeholder="código" type="text" name="cod_02" />
<input placeholder="valor" type="text" name="valor_02" />
<br />
<input placeholder="código" type="text" name="cod_03" />
<input placeholder="valor" type="text" name="valor_03" />
<br />
<input placeholder="código" type="text" name="cod_04" />
<input placeholder="valor" type="text" name="valor_04" />

  • Buddy, it didn’t work out the way I mentioned. It’s not grouping by code. It’s just adding up the total value.

  • @Y.Menon I hadn’t noticed this detail... I’ll rephrase the answer...

  • @Y.Menon I believe it will now work.

  • perfect! thank you!

Browser other questions tagged

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