Swap Button for Auto Sum

Asked

Viewed 83 times

1

How I change the button calcular by auto sum with javascript !

[Example] when typing in input name="campo1" he adds to the input name="campo2" automatically without needing the button calcular

is a currency simulator because I want to put the R$ in the input name="campo1" and so when I put the money he will give me the value at the same time on input name="campo2"

Obs: the input name="campo2"is multiplying by 23 and 25 i just want to leave auto sum to take off the button calcular

this is the code : SCRIPT :

    <script>
function soma() 
{
    var valor;
    var campo = form.campo1.value;
    if(campo >=1  && campo < 99){
        valor=23;
    }else{
        valor=25;
    }

    form.campo4.value = parseInt(campo) * parseInt(valor) 
}
</script>

HTML :

    <form name="form">
<input name="campo1" id="demo4"><br> 
<input name="campo2" value="" id="demo3" style="display: none;"><br>  
<input name="campo4" readonly id="resultado"><br>
<input type="button" onclick="soma()" value="CALCULAR">
</form>

2 answers

1


To have a code to be interpreted when you type you can use the event keyup which you can listen to directly on the html label:

<input name="campo1" id="demo4" onkeyup="soma()"><br> 

Example:

function soma() 
{
    var valor;
    var campo = form.campo1.value;
    if(campo >=1  && campo < 99){
        valor=23;
    }else{
        valor=25;
    }

    form.campo4.value = parseInt(campo) * parseInt(valor) 
}
<form name="form">
<input name="campo1" id="demo4" onkeyup="soma()"><br> 
<input name="campo2" value="" id="demo3" style="display: none;"><br>  
<input name="campo4" readonly id="resultado"><br>
</form>

It would even be better to link to the event entirely by javascript with:

document.getElementById("demo4").addEventListener("keyup", soma));
  • Thanks Isac ! know how I limit also the max of number type 3 before , and 2 after the , ??

  • @Andrejunior If you’re talking about currency formatting, you already have several questions for that, such as this

  • Thanks again helped me a lot !

  • @You’re welcome, I’m glad I could help.

0

Here is a suggestion, sending the value entered directly into onkeyuphere:

<input name="campo1" id="demo4" onkeyup="soma(Number(this.value))">

var resultado = document.getElementById('resultado');
function soma(valor) {
  var multiplicador = valor >= 1 && valor < 99 ? 23 : 25;
  resultado.value = multiplicador * valor;
}
<form name="form">
  <input name="campo1" id="demo4" onkeyup="soma(Number(this.value))"><br>
  <input name="campo2" value="" id="demo3" style="display: none;"><br>
  <input name="campo4" readonly id="resultado"><br>
</form>

Browser other questions tagged

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