Change Button for Auto Soma

1

How do I change the calcular button to auto sum with javascript!

[Example] typing in input name="campo1" adds with input name="campo2" automatically without needing calcular button

It is a coin simulator because I want to R$ in input name="campo1" and so when I for the money it will give me the value at the same time in input name="campo2"

Note: input name="campo2" is multiplying by 23 and 25 I just want to leave auto sum to get the calcular button

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>
    
asked by anonymous 13.10.2017 / 03:32

2 answers

1

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

<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 connect to the event entirely by javascript with:

document.getElementById("demo4").addEventListener("keyup", soma));
    
13.10.2017 / 03:41
0

Here's a suggestion, sending the value entered directly into onkeyup here:

<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>
    
13.10.2017 / 07:33