How to make a transition button similar to Google Translator for a mathematical operation

Asked

Viewed 420 times

3

I’m creating a little calculator that converts Kilograms in Pounds
and Pounds in Kilograms.

My goal is to insert a value in a first input and display the result in a second input which comes next. For example:

<input id='in' value='1' type='text'/>             <!-- O usuário insere 1KG no primeiro input para converter em Pounds -->
<input id='out' value='2.20462262' type='text'/>   <!-- E o resultado aparecerá aqui no seguindo input: 2.20462262 -->

The basic concept is this! But now I wanted there to be a button like the Google Translator in the middle of these two inputs, in which the calculation units were reversed, that is to say at the beginning we would be calculating - (KG para Pounds), Clicking on the button will reverse the calculation/weight units and now we will be calculating - (Pounds para KG). All this in one button.

Better explaining. At the beginning we would be calculating how many kilos would be a value X in Pounds:

.caixa {display: inline-block;}
<div class="caixa">
    Quilogramas<br />
    <input id='field1' value='50' type='text'/>
</div>
<div class="caixa"><button id='switch'>Inverter Unidade</button></div>
<div class="caixa">
    Pounds<br />
    <input id='field2' value='110.23' type='text'/>
</div>

Clicking the button Inverter Unidade, it reverses the units of weight and can now calculate how many Pounds will be a value X in Quilogramas:

.caixa {display: inline-block;}
<div class="caixa">
    Pounds<br />
    <input id='field1' value='100' type='text'/>
</div>
<div class="caixa"><button id='switch'>Inverter Unidade</button></div>
<div class="caixa">
    Quilogramas<br />
    <input id='field2' value='45.35' type='text'/>
</div>

Did you understand what I want to do? Here is the code of what I have so far:

function calcPD(){
    var pound = document.getElementById("field1").value;
    var calc = quilos / 2.2046;
    var resul = document.getElementById("field2").value=calcular.toFixed(2);    
}

function calcKg(){      
    var kg = document.getElementById("field1").value;
    var calc = quilo * 2.2046;
    var resul = document.getElementById("field2").value=calcular.toFixed(2);                            
}
  • 2

    Type that?

  • I understand what he wants and I’ve already developed a solution.

  • @devgaspa has how to post the solution?

1 answer

2


Expensive,

I have developed a solution for your need, any doubt just comment, but the code is very eligible. Here is also an example on jsFiddle if you prefer.

var conversor = {
    // Valores do Objeto conversor
    valor : document.getElementById('iptValor'),
    resultado : document.getElementById('iptResultado'),
    labelValor : document.getElementById('lblValor'),
    labelResultado : document.getElementById('lblResultado'),
    unidade : 2.2046,
    operacao : 'Kilos',
    // Valores Funções do Objeto conversor
    Kilos : function() {
      return this.valor.value * this.unidade;
    },
    Pounds : function() {
      return this.valor.value / this.unidade;
    },
    trocar : function() {
      this.labelResultado.innerText = this.operacao;
      this.operacao = this.operacao === 'Kilos' ? 'Pounds' : 'Kilos';
      this.labelValor.innerText = this.operacao;
      this.calcular(this.valor.value);
    },
    // Função para conversão.
    calcular : function() {
      if(this.valor.value != '')
      	this.resultado.value = conversor[this.operacao]().toFixed(4); // .toFixed(4) fixa 4 casas decimais.
    }
}

// Adiciona o evento click ao botão trocar
document.getElementById('trocar').addEventListener('click', function() {
	conversor.trocar(); // Chama a função que troca a conversão
}, false);
// Adiciona o evento click ao botão calcular
document.getElementById('calcular').addEventListener('click', function() {
	conversor.calcular(); // Chama a função que calcula a conversão
}, false);
<div>
    <!-- Label + Input referente ao valor base da conversão -->
    <label id="lblValor" for="iptValor">Kilos</label>
    <input type="number" id="iptValor">
    <!-- Neste botão será adiciona um evento de click -->
    <button id="trocar">Trocar</button>
    <!-- Label + Input referente ao resultado da conversão -->
    <label id="lblResultado" for="iptResultado">Pounds</label>
    <input type="number" id="iptResultado">
    <!-- Neste botão será adiciona um evento de click -->
    <button id="calcular">Calcular</button>
</div>

  • 1

    hello, your answer totally depends on an external resource, is recommended to provide a context when using such links, in addition the OS supports executable javascript codes, to insert use Ctrl + M in the editor

  • @Penalty Thank you :)

  • Hello @devgaspa! This is exactly what I need to finish my code. Thank you so much for your contribution. But... When copying the code and running on my machine, it shows an error regarding the "addeventlistener" event. It is not possible to read such property, the same is NULL. What can it be? (I’m sure it’s bullshit, but I still don’t know how to solve).

  • @Luizsantos is probably not finding the element to add the event or is trying to add to an invalid element for assignment. put your code here or in a jsfiddle for me to analyze.

  • That’s the problem @devgaspa. I’m just copying and pasting your code on a clean page. Just to run even locally and nothing.

  • @Luizsantos You changed the HTML ?

  • @devgaspa No. I just copied and pasted everything.

  • @Luizsantos you are declaring the script last within the tag <body>?

  • No. I changed it, pegoou! Thanks again @devgaspa!! But why is that? I know the JS language is interpreted.. It has something to do with it?

  • @Luizsantos It has to do yes, it occurred because before rendering the elements inside the tag <body> He interpreted javascript and how the addition of events in the elements is done in an unexamined way javascript tried to add events in elements that did not exist until then. for this not to happen it is necessary to create an event, for example, window.addEventListener('DOMContentLoaded', fn, false) to execute the code only after the page loaded.

  • @devgaspa got it. Thanks for your help!!

Show 6 more comments

Browser other questions tagged

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