How to make calculations by clicking the button and placing the result in another field

Asked

Viewed 136 times

-2

How to make this form do this account: ((a-b)+(((a-b)*0,1)+((a-b)*0,1268))))/240?

I want the "property price" and "entry value" fields to be filled in and then when you click on "calculate", the result will appear in the "result".

If (a) is equal to 1000 and (b) equal to 100 the result is 4,6005. And after you have done the calculation, click "clean" to clear the fields.

  • a = price of the property
  • b = input value
  • 0,1, 0,1268 and 240 are fixed values

      form{
                    width: 220px;
                    height: 360px;
                    background: #002776;                
                    border-radius: 4px;                           
                    box-shadow: 0 0 20px 1px rgba(0,0,0,0.7);
                    padding: 0 2% 2% 2%;
                    box-sizing: border-box;
                }

                .tsmr{
                   text-align: center;
                   color: #fff; 
                   margin: 0 0 10% 0;              
                   padding: 5% 0 5% 0;
                   font-size: 20px;
                   font-family: 'Roboto', sans-serif;
                   box-shadow: 0 0 20px 1px rgba(0,0,0,0.7);
                }

                .sml{
                width: 96%;
                margin: 1% 0 4% 0;
                }
      
                #btn, #btn1{
                width: 100%;
                height: 30px;
                margin: 9% 0 0 0; 
                font-weight: bold;
                font-family: 'Roboto', sans-serif;
                box-shadow: 0 0 20px 1px rgba(0,0,0,0.7);
                background: #fff;
                color: #000;
                border-radius: 4px;
                letter-spacing: 2px;
                border: none;
                font-size: 15px;
                cursor: pointer; 
                }

                #lbs{
                     font-size: 13px;
                     color: #fff;
                     letter-spacing: 1px;
                     font-family: 'Roboto Condensed', sans-serif;
                     
                }

                #lbs2{
                     font-size: 13px;
                     color: #fff;
                     letter-spacing: 1px;
                     font-family: 'Roboto Condensed', sans-serif;
                     
                }

                #lbs3{
                     font-size: 13px;
                     color: #fff;
                     letter-spacing: 1px;
                     font-family: 'Roboto Condensed', sans-serif;
                     
                }
                
               <form>

               <p class= "tsmr">SIMULADOR</p>

               <label id="lbs">PREÇO DO IMÓVEL:</label>
               <input class="sml" type="text" value="">

               <label id="lbs2">VALOR DA ENTRADA:</label>
               <input class="sml" type="text">

               <label id="lbs3">RESULTADO:</label>
               <input class="sml" type="text">

               <button id="btn" type="buttom">CALCULAR</button>
               <button id="btn1" type="buttom">LIMPAR</button>
                    
               </form>

  • did not try any javascript code?

  • If any answer has served you mark it (the best) as accepted, see https://i.stack.Imgur.com/evLUR.png

3 answers

1

The first thing I’d do is put a id in each input, so it becomes easier to find them. A another answer ended up using selectors as '#lbs + input', to get the input which comes just after the respective label. It’s not wrong, but if the label is not used for anything, I prefer to add a id in the input and pick it up directly.

And so that the form do not submit, you must use preventDefault on the buttons, so the form is not submitted and you remain on the same page. And to clear the form, you can use input type="reset", that reset the fields for the initial values (and how they start empty, already seems to be what you need). Using a Event Listener proper to clean the form would only make sense if the values were different from the initial ones.

And if you really want to check if valid numbers have been entered I suggest using parseFloat.

And a point I don’t like another answer is that it checks twice if the values are numbers:

if (isNaN(a) || isNaN(b)) alert('Insira apenas números')
if (a && b && !(isNaN(a) || isNaN(b))) { etc...

But this is redundant and unnecessary. Just test isNaN once for each value and if they are not numbers, use return to exit the function (i.e., if the value is invalid, nor executes the remainder). And I took the opportunity to validate if the value is greater than zero (because it does not seem to me to accept negative price, for example - already the input, I understand that can be zero).

Another detail is that the calculation ((a-b)+(((a-b)*0,1)+((a-b)*0,1268)))/240 can be simplified. Basically, you are doing (disregarding the split by 240):

valor + (valor * 0.1) + (valor * 0.1268)

That in the end it’s the same thing:

valor * (1 + 0.1 + 0.1268)

Which is ultimately the same as:

valor * 1.2268

I mean, the calculation would just be ((a - b) * 1.2268) / 240.

And I also gave better names for variables. It may seem like a silly detail, but give better names help a lot when programming.

I removed the CSS because it does not interfere with the algorithm, and to make it shorter and focus only on Javascript and HTML, which are the focus of the question.

Finally, toFixed always returns the value using the point as decimal separator. But as the question implies that you want to use the comma, then exchange it for toLocaleString:

document.querySelector('#btn').addEventListener('click', function(e) {
    e.preventDefault();
    let preco = parseFloat(document.querySelector('#preco').value);
    if (isNaN(preco) || preco <= 0) {
        alert('Preço deve ser um número maior que zero');
        return; // sai da função (nem precisa ler o valor da entrada porque não adianta)
    }
    let entrada = parseFloat(document.querySelector('#entrada').value);
    if (isNaN(entrada) || entrada < 0) {
        alert('Entrada deve ser um número maior ou igual a zero');
        return; // sai da função
    }
    let result = ((preco - entrada) * 1.2268) / 240;
    // usar toLocaleString, o locale 'pt-BR' (português do Brasil) usa a vírgula como separador decimal
    document.querySelector('#resultado').value = result.toLocaleString('pt-BR', { minimumFractionDigits: 4, maximumFractionDigits: 4 });
});
<form>
  <p class="tsmr">SIMULADOR</p>
  <label id="lbs">PREÇO DO IMÓVEL:</label>
  <input id="preco" class="sml" type="text" value=""><br>
  <label id="lbs2">VALOR DA ENTRADA:</label>
  <input id="entrada" class="sml" type="text"><br>
  <label id="lbs3">RESULTADO:</label>
  <input id="resultado" class="sml" type="text"><br>
  <button id="btn" type="button">CALCULAR</button><br>
  <button id="btn1" type="reset">LIMPAR</button>
</form>

I also put a semicolon at the end of the lines. It may sound "fresh," and I know that Javascript "accepts" the semicolon code and "works," but it avoids some bizarre situations that can occur if you don’t use them, like that one and that one (see more about this here).

1

You can solve this with pure Javascript, follow the code I wrote to help you.

Ps.: HTML and CSS are your originals, I just added Javascript. Click on Execute at the end of the code.

var calcButton = document.querySelector('#btn');
calcButton.addEventListener('click', e => {
  e.preventDefault()
  var a = document.querySelector('#lbs + input').value;
  var b = document.querySelector('#lbs2 + input').value;
  if (isNaN(a) || isNaN(b)) alert('Insira apenas números')
  if (a && b && !(isNaN(a) || isNaN(b))) {
    var inputResult = document.querySelector('#lbs3 + input');
    var rawResult =  ((a-b)+(((a-b)*0.1)+((a-b)*0.1268)))/240
    var result = rawResult.toFixed(4)
  inputResult.value = result
  }
});

var cleanButton = document.querySelector('#btn1');
cleanButton.addEventListener('click', e => {
  e.preventDefault()
    document.querySelector('#lbs + input').value = ''
    document.querySelector('#lbs2 + input').value = ''
    document.querySelector('#lbs3 + input').value = ''
});
form {
  width: 220px;
  height: 360px;
  background: #002776;
  border-radius: 4px;
  box-shadow: 0 0 20px 1px rgba(0, 0, 0, 0.7);
  padding: 0 2% 2% 2%;
  box-sizing: border-box;
}

.tsmr {
  text-align: center;
  color: #fff;
  margin: 0 0 10% 0;
  padding: 5% 0 5% 0;
  font-size: 20px;
  font-family: 'Roboto', sans-serif;
  box-shadow: 0 0 20px 1px rgba(0, 0, 0, 0.7);
}

.sml {
  width: 96%;
  margin: 1% 0 4% 0;
}

#btn,
#btn1 {
  width: 100%;
  height: 30px;
  margin: 9% 0 0 0;
  font-weight: bold;
  font-family: 'Roboto', sans-serif;
  box-shadow: 0 0 20px 1px rgba(0, 0, 0, 0.7);
  background: #fff;
  color: #000;
  border-radius: 4px;
  letter-spacing: 2px;
  border: none;
  font-size: 15px;
  cursor: pointer;
}

#lbs {
  font-size: 13px;
  color: #fff;
  letter-spacing: 1px;
  font-family: 'Roboto Condensed', sans-serif;

}

#lbs2 {
  font-size: 13px;
  color: #fff;
  letter-spacing: 1px;
  font-family: 'Roboto Condensed', sans-serif;

}

#lbs3 {
  font-size: 13px;
  color: #fff;
  letter-spacing: 1px;
  font-family: 'Roboto Condensed', sans-serif;

}
<form>

  <p class="tsmr">SIMULADOR</p>

  <label id="lbs">PREÇO DO IMÓVEL:</label>
  <input class="sml" type="text" value="">

  <label id="lbs2">VALOR DA ENTRADA:</label>
  <input class="sml" type="text">

  <label id="lbs3">RESULTADO:</label>
  <input class="sml" type="text">

  <button id="btn" type="buttom">CALCULAR</button>
  <button id="btn1" type="buttom">LIMPAR</button>

</form>

0


No calculate button, formatting the output with comma

    function reset() {
      document.getElementById("idForm").reset();
    }

    function id(el) {
      return document.getElementById( el );
    }
    function total( un, qnt ) {

        if (isNaN(un) || isNaN(qnt)){
            reset();
        }

        return parseFloat(((un-qnt)+(((un-qnt)*0.1)+((un-qnt)*0.1268)))/240);
        
      
    }

    window.onload = function() {
      id('preco').addEventListener('keyup', function() {
        var result = total( this.value , id('entrada').value );
        id('resultado').value = String(result.toFixed(4)).formatMoney();
      });

      id('entrada').addEventListener('keyup', function(){
        var result = total( id('preco').value , this.value );
        id('resultado').value = String(result.toFixed(4)).formatMoney();
      });
    }

    String.prototype.formatMoney = function() {
      var v = this;

      if(v.indexOf('.') === -1) {
        v = v.replace(/([\d]+)/, "$1,00");
      }

      v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
      v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
      v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");

      return v;
    };
      form{
                    width: 220px;
                    height: 290px;
                    background: #002776;                
                    border-radius: 4px;                           
                    box-shadow: 0 0 20px 1px rgba(0,0,0,0.7);
                    padding: 0 2% 2% 2%;
                    box-sizing: border-box;
                }

                .tsmr{
                   text-align: center;
                   color: #fff; 
                   margin: 0 0 10% 0;              
                   padding: 5% 0 5% 0;
                   font-size: 20px;
                   font-family: 'Roboto', sans-serif;
                   box-shadow: 0 0 20px 1px rgba(0,0,0,0.7);
                }

                .sml{
                width: 96%;
                margin: 1% 0 4% 0;
                }
      
                #btn1{
                width: 100%;
                height: 30px;
                margin: 9% 0 0 0; 
                font-weight: bold;
                font-family: 'Roboto', sans-serif;
                box-shadow: 0 0 20px 1px rgba(0,0,0,0.7);
                background: #fff;
                color: #000;
                border-radius: 4px;
                letter-spacing: 2px;
                border: none;
                font-size: 15px;
                cursor: pointer; 
                }

                #lbs{
                     font-size: 13px;
                     color: #fff;
                     letter-spacing: 1px;
                     font-family: 'Roboto Condensed', sans-serif;
                     
                }

                #lbs2{
                     font-size: 13px;
                     color: #fff;
                     letter-spacing: 1px;
                     font-family: 'Roboto Condensed', sans-serif;
                     
                }

                #lbs3{
                     font-size: 13px;
                     color: #fff;
                     letter-spacing: 1px;
                     font-family: 'Roboto Condensed', sans-serif;
                     
                }
              <form id="idForm">

               <p class= "tsmr">SIMULADOR</p>

               <label id="lbs">PREÇO DO IMÓVEL:</label>
               <input class="sml" id="preco" type="text" value="">

               <label id="lbs2">VALOR DA ENTRADA:</label>
               <input class="sml" id="entrada" type="text">

               <label id="lbs3">RESULTADO:</label>
               <input class="sml" id="resultado" type="text">
              
               <button id="btn1" type="button" onclick="reset()">LIMPAR</button>
                    
               </form>



on the comment "How this script would look to do the calculation in a tag <p>?"

  
//var sn = getParameterByName('pt');

//supor que sn retornado acima seja 30
var sn=30;

document.getElementById("vj2p").innerHTML = "Preço: "+sn;

document.getElementById("receptor").innerHTML = sn;

    var calculador = document.getElementById("calculador").innerHTML;
    var resultado = (sn*calculador).toFixed(2);
    document.getElementById("calculador").innerHTML=resultado;


   
 <p id="vj2p"></p>

 <p id="receptor"></p> <p id="calculador">0.1268</p>
 

sfor comments on calculations with Real format R$ 1000,00 + R$ 100,00

    const v1 = 'R$ 1.000,00';
    const v2 = 'R$ 100,00';
     let val1 = v1.replace('R$','').replace(/\./gi,'').replace(/,/gi,'.');
     let val2 = v2.replace('R$','').replace(/\./gi,'').replace(/,/gi,'.');
     
    val1 = Number(val1);
    val2 = Number(val2);

    console.log((val1 + val2).toLocaleString('pt-BR', { style: 'currency', currency: 'brl' }));

  • Good afternoon. How would this script look to make the calculation in a <p> tag? Ex:. (<p id="receiver"></p> </p> <p id="calculator"></p> ) The receiver receives the variable and the calculator stores a fixed value (0.1268) to calculate by the receiver. The result should appear in the calculator. I tried with this script you posted, but I could only do input.

  • @jairoolindino, and how would the receiver (a tag paragraphe <p>) receive a variable? Where would this variable come from?

  • The <p> tag takes the variable from a form, which is on another page. I use this script to receive the variable:

  • Function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[]]/g, '$&'); var regex = new Regexp('[?&]' + name + '(=([ &#]*)|&|#|$|)'), Results = regex.exec(url); if (!Results) Return null; if (!Results[2]) Return ''; Return decodeURIComponent(Results[2].replace(/+/g, ' '); } var Sn = getParameterByName('pt'); Document.getElementById("vj2p"). innerHTML = "Price: "+Sn;

  • The page that sends the variable uses this script: <form action="destination.html" method="GET"></form>

  • @jairoolindino, kind of confused, was <p id="receiver"></p> <p id="calculator"></p> and now enters a new getElementById("vj2p"). Better formulate a question with the proper codes. Anyway at the end of the answer I added something to see if this is it.

  • Good morning, Leo! I got it with the code you posted. it looked like this: window.onload = Function() ? var Sn= 0.1268; var calculator = Document.getElementById("vj2p2"). innerHTML; var result = (Sn*calculator). toLocaleString('en-BR', { style: 'currency', currency: 'Brl' }); Document.getElementById("vj2p3"). innerHTML=result; }

  • Leo, do you know if it is possible to calculate using currency format? Ex.: R$ 1,000.00 + R$ 100.00

  • @jairoolindino, mathematical calculations only in American format. You have to highlight and transform the numerical part in American format, perform the operation and then format Brazilian to present on screen.

Show 4 more comments

Browser other questions tagged

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