How to make a switch button/reverse button. Similar to Google translate - javascript

I'm make a little calculator that convert KG in Pounds and Pounds in KG and write on an input. But, I want make this with only one button to calculate! Understand?
KG to POUNDS -> KG * 2.2046
POUNDS to KG -> POUNDS / 2.2046
Example 1:
Field 1: 50 kg
....calc...
Field 2 (result): 110.23 Pounds
Then there will be the button for me to change the function (Button of Google Translate to change the languages in every click) I click and ..
Example 2:
Field 1: 100 pounds
...calc...
Field 2 (result): 45.35
Can you understand what I do?
function calcPD(){
var pound = document.getElementById("field1").value;
var calc = quilos / 2.2046;
var resul = document.getElementById("pound").value=calcularr.toFixed(2);
}
function calcKg(){
var kg = document.getElementById("field1").value;
var calc = quilo * 2.2046;
var resul = document.getElementById("pound").value=calcular.toFixed(2);
}
funcion invert(){
???
}

I think what you're looking for is just a simple variable to keep track of what "mode" you are in. I've built an example for you to see how this would work (I used bootstrap to make it pretty, but obviously that's optional):
https://jsfiddle.net/DTcHh/13851/
HTML
<div class="container">
<div class="row">
<div class="col-xs-6">
Input:
<input id="inputNum" class="form-control" type="number"></input>
</div>
<div class="col-xs-6">
Output:
<input id="outputNum" class="form-control" type="text" disabled></input>
</div>
</div>
<span id="modeText">lbs to kg</span>
<button id="switch" class="btn pull-right">Switch</button>
</div>
Javascript
//0 = lbs to kg, 1 = kg to lbs
var mode = 0;
var inputNum = $("#inputNum");
var outputNum = $("#outputNum");
var switchMode = $("#switch");
var modeText = $("#modeText");
var calculateKgs = function() {
outputNum.val(inputNum.val()/2.2046);
};
var calculateLbs = function() {
outputNum.val(inputNum.val()*2.2046);
};
var calculate = function() {
if(mode == 0)
calculateKgs();
else
calculateLbs();
};
inputNum.change(calculate);
inputNum.keyup(calculate);
switchMode.click(function() {
if(mode) {
mode = 0;
modeText.text("lbs to kg");
}
else {
mode = 1;
modeText.text("kg to lbs");
}
calculate();
});

Sounds like you need to use innerHtml. Some basic pseudo logic for you:
var a = document.getElementById("one").innerHtml;
var b = document.getElementById("two").innerHtml;
document.getElementById("one").innerHtml = b;
document.getElementById("two").innerHtml = a;

Related

Jquery / javascript error to get live result in my project

Currently I am working in a Bitcoin live price project with jquery. Now I need to develop a live price difference percentage change calculator. Calculator is working fine. But not working automatically when Bitcoin live price changing. I need to edit in input. Keyup event needed for working. I need to make it as always automatically. Please make it as automatically without keyup.. I created a Codepen page for it. https://codepen.io/toolsim/pen/Rwywjap . My codes;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="text" id="btc-price" class="main01 dz-none from01 for-copy01 input bldo te-cen" value="">
<input type="text" value="25000" class="main02 percentagez to01 input bldo te-cen">
<input type="text" class="rz-result result01 input bldo te-cen">
<script type="text/javascript">
$(document).on("change keyup blur", ".main02", function() {
var first = Number($('.from01').val());
var second = Number($('.to01').val());
var minus = second - first; // 2000 - 1000 = {1000 = minus}
var divide = (minus / first); // 1000 / 1000 = 1
var multiply = divide * 100; // 1 * 100 = 100%
$('.result01').val(Number(multiply).toFixed(2));
});
</script>
<script type="text/javascript">
let weburl = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade');
let stockPriceInput = document.querySelector('#btc-price');
let lastPrice = null;
weburl.onmessage = (event) => {
let stockObject = JSON.parse(event.data);
let price = parseFloat(stockObject.p).toFixed(2);
stockPriceInput.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? 'green' : 'red';
stockPriceInput.value = price;
lastPrice = price;
};
</script>
maybe like this:
function set_bts(_price){
$('.main01').val(_price);
var first = Number($('.from01').val());
var second = Number($('.to01').val());
var minus = second - first; // 2000 - 1000 = {1000 = minus}
var divide = (minus / first); // 1000 / 1000 = 1
var multiply = divide * 100; // 1 * 100 = 100%
$('.result01').val(Number(multiply).toFixed(2));
}
var weburl = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade');
weburl.onmessage = function(event){
var stockObject = JSON.parse(event.data);
var price = parseFloat(stockObject.p).toFixed(2);
set_bts(price)
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="text" id="btc-price" class="main01 from01" value="">
<input type="text" value="25000" class="to01">
<input type="text" class="result01">

JavaScript - is there any way (without using html event attributes) to get 3 different input values to contribute towards a sum?

I am completing the 57 programming exercises book by Brian P. Hogan.
With most of these exercises, I've tried to develop a GUI.
In the following exercise, I want to calculate the Simple Interest of a Principal value over a period of years. Simply put:
var yearlyInterest = Principal * (Percentage(whole number) /= 100)
(yearlyInterest * numberOfYears) + Principal
// outputs total amount at the end of investment over a period of however many years
As you can see in the example above, there are three core inputs - Principal, Percentage and Time.
When creating the graphical user interface, I am struggling to get all of these core inputs to calculate the result simultaneously.
The following code only manages to calculate the result once I enter the number for the Time input. (excuse my poor coding skills i.e. global variables, I'm only up to exercise 12!)
HTML
<!DOCTYPE html>
<html lang="en">
<body>
<label for="principal">Principal</label>
<input type="number" class="principal" style="border-color: black;">
<label for="percentage">Percentage</label>
<input type="number" class="percentage" style="border-color: black;">
<label for="time">Time</label>
<input type="number" class="time" style="border-color: black;">
<div id="result"></div>
</body>
<script src="simpleInterest.js"></script>
</html>
JS
var principal = document.getElementsByClassName("principal");
var percentage = document.getElementsByClassName("percentage");
var time = document.getElementsByClassName("time");
var output = document.querySelector("#result");
var result;
var newResult;
var finalOutput;
document.addEventListener('input', function (event) {
if ( event.target.classList.contains( 'principal' ) ) {
var newPrincipal = principal[0].value;
result = newPrincipal;
}
if ( event.target.classList.contains( 'percentage' ) ) {
var newPercentage = percentage[0].value;
newResult = result * (newPercentage / 100);
}
if ( event.target.classList.contains( 'time' ) ) {
var newTime = time[0].value;
finalOutput = (newResult * newTime) + Number(result);
}
output.innerHTML = `${finalOutput ? finalOutput : ""}`
}, false);
Could somebody please show me an effective way to simultaneously calculate something based on each input event and output it using the .innerHTML method?
Thanks!
You need to get the values of all the inputs, not just the one that the user is currently typing in. Define a single function that does this, and add it as an event listener for all 3 inputs.
var principal = document.querySelector(".principal");
var percentage = document.querySelector(".percentage");
var time = document.querySelector(".time");
var output = document.querySelector("#result");
function calcInterest() {
var newPrincipal = parseFloat(principal.value);
var newPercentage = parseFloat(percentage.value);
var newTime = parseFloat(time.value);
if (!isNaN(newPrincipal) && !isNaN(newPercentage) && !isNaN(newTime)) {
var result = newPrincipal + newTime * newPrincipal * newPercentage / 100;
output.textContent = result;
}
}
principal.addEventListener("input", calcInterest);
percentage.addEventListener("input", calcInterest);
time.addEventListener("input", calcInterest);
<label for="principal">Principal</label>
<input type="number" class="principal" style="border-color: black;"><br>
<label for="percentage">Percentage</label>
<input type="number" class="percentage" style="border-color: black;"><br>
<label for="time">Time</label>
<input type="number" class="time" style="border-color: black;"><br> Result:
<div id="result"></div>
Create function to calculate, and call this function instead of just executing some code. Something like that:
var principal = document.getElementsByClassName("principal")
var percentage = document.getElementsByClassName("percentage")
var time = document.getElementsByClassName("time")
var output = document.querySelector("#result")
var result
var newResult
var finalOutput
var calculate = () => {
var newPrincipal = principal[0].value;
result = newPrincipal
var newPercentage = percentage[0].value
newResult = result * (newPercentage / 100)
var newTime = time[0].value
finalOutput = (newResult * newTime) + Number(result)
}
document.addEventListener('input', function (event) {
if ( event.target.classList.contains( 'principal' ) ) {
calculate();
}
if ( event.target.classList.contains( 'percentage' ) ) {
calculate();
}
if ( event.target.classList.contains( 'time' ) ) {
calculate();
}
output.innerHTML = `${finalOutput ? finalOutput : ""}`
}, false);

how can i make my calculation using math.sqrt right?

I just want to get the square root of total2 .. but it won't appear in the selected box ..
here is the javascript codes.
i'll comment the html codes.
function myFunction() {
var q1 = document.getElementById("qinput1").value;
var q2 = document.getElementById("qinput2").value;
var q3 = document.getElementById("qinput3").value;
var total = parseInt(q1) + parseInt(q2) + parseInt(q3);
document.getElementById("ainput3").value=total;
var a1 = document.getElementById("ainput1").value;
var a2 = document.getElementById("ainput2").value;
//from the total we got, lets assign it a variable for further calculation
var a3 = document.getElementById("ainput3").value=total;
var total2 = parseInt(a1)*parseInt(a2)/ parseInt(a3);
document.getElementById("ansA").value = total2;
var total3 = math.sqrt(parseInt(total2));
document.getElementById("sqaureD").value = total3;
}
function myShapes() {
document.getElementById('squareA').style.display =
document.getElementById('shapes').value == 'Square' ? 'block' : 'none'
}
<form action="" id="fcalculation">
<fieldset>
<legend>Calculation of qu</legend>
<label><i>Ultimate bearing capacity</i> <b>(qu) = </b></label>
<input id="qinput1" type="text" placeholder="c'NcFcsFcdFci"/> +
<input id="qinput2" type="text" placeholder="qNqFqsFqdFqi"/> +
<input id="qinput3" type="text" placeholder="½βγNFγsFγdFγi"/>
</fieldset>
</form>
it seems that the calculation part at the very end is not working. sorry its my first time to code.
Classname is Math not math
Try replacing
var total3 = math.sqrt(parseInt(total2,10));
with
var total3 = Math.sqrt(parseInt(total2,10));
Also, looking at your markup, there are no fields with id ainput1, ainput2 and ainput3.

NaN error on form submission [duplicate]

This question already has answers here:
Reading numbers from inputs with JavaScript always returns NaN
(8 answers)
Closed 7 years ago.
I'm attempting to write a simple JavaScript program that calculates the cost of gas based on some parameters from a form. Upon form submission, I get a NaN error inside of the "calculatedMonthlyCost" div.
Can anybody tell me what I'm doing wrong? Is there a better way of doing this?
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
<script>
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
var userCostOfGas = document.forms[0].costOfGas.value;
var userMPG = document.forms[0].vehicleMPG.value;
var userNumMiles = document.forms[0].numMiles.value;
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};
</script>
You were getting the values on page load (when they were empty). You just need to get the values inside the onsubmit event listener, and to convert them to Numbers.
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var userCostOfGas = +document.forms[0].costOfGas.value; // < Move these lines here and
var userMPG = +document.forms[0].vehicleMPG.value; // < add a plus sign before them
var userNumMiles = +document.forms[0].numMiles.value; // <
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
If you only want 2 decimals, you can change this line:
calculatedMonthlyCost.innerHTML = (costs.weeklyCost).toFixed(2);
Demo:
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var userCostOfGas = +document.forms[0].costOfGas.value; // < Move these lines here and
var userMPG = +document.forms[0].vehicleMPG.value; // < add a plus sign before them
var userNumMiles = +document.forms[0].numMiles.value; // <
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = (costs.weeklyCost).toFixed(2);
};
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
You save the value of your inputs before the onsubmit method is called. This actually saves a blank value since the variables are set before the user inputs a value and it's not dynamic. The values need to be checked on submit.
document.forms[0].onsubmit = function(e) {
var userCostOfGas = parseInt(document.forms[0].costOfGas.value,10);
var userMPG = parseInt(document.forms[0].vehicleMPG.value,10);
var userNumMiles = parseInt(document.forms[0].numMiles.value,10);
e.preventDefault();
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};

Celsius and Fahrenheit Converter- JavaScript

I want to make a webpage that has two text boxes, a Celsius and Fahrenheit box. In between them, there is a convert button which converts Celsius to Fahrenheit and Fahrenheit to Celsius. If there is letters in either box, I want to cancel the converting and an alert pop up saying "Only numbers please!" So far, I haven't figured out how to get the alert and when I type numbers in the Celsius box, it always says the number -18 in the same box. Fahrenheit is fine.
HTML:
<html>
<head>
<title>Temparature Converter</title>
<script type="text/javascript" src="tempconversion.js"></script>
</head>
<body>
Celsius: <input id="c" onkeyup="convert('C')">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
Fahrenheit: <input id="f" onkeyup="convert('F')">
</body>
</html>
JavaScript:
function convertTemp(degree) {
if (degree == "C") {
F = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(F);
} else {
C = (document.getElementById("f").value -32) * 5 / 9;
document.getElementById("c").value = Math.round(C);
}
}
Note: I got some code from W3Schools so I think the onkeyup convert is a little funny. If possible, please notify me how it has to change as well as the JavaScript.
There is no need for the onkeyup attributes, since they original code from W3Schools was designed to instantly update values as they were entered.
I did modify the functionality to clear of original value, that way the conversion button can work both ways with a simple code.
Here's a quick JavaScript to do the job:
function convertTemp() {
// Set the initial variables for c (Celsius) and f (Fahrenheit)
var c = document.getElementById('c'), f = document.getElementById('f');
// Test if there is a value for Celsius
if(c.value != '') {
// Set the value for Fahrenheit
f.value = Math.round(c.value * 9 / 5 + 32);
// Clear the value for Celsius
c.value = '';
// If there isn't a value for Celsius
} else {
// Set the value for Celsius
c.value = Math.round((f.value - 32) * 5 / 9);
// Clear the value for Fahrenheit
f.value = '';
}
}
And its accompanying HTML:
Celcius:<input id="c">
Fahrenheit:<input id="f">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
It can be tested at: http://jsfiddle.net/bhz6uz54/
Something to remember about simple code, like this, there is nothing to verify the supplied values are acceptable. A little regex can act as validation, but how it would be implemented depends on how you want to flag the problem.
I personally hate Do-it Buttons so I'd go with a more dynamic solution:
// Get the Input elements:
var $f = document.getElementById("f");
var $c = document.getElementById("c");
function FC_CF() {
var temp; // Will hold the temperature value
var $targ; // Used to target the element we're not typing into:
if (this.id === "c") { // If we're typing into #c...
$targ = $f; // use #f as target element
temp = (this.value * 9 / 5) + 32; // C2F
} else {
$targ = $c;
temp = (this.value - 32) * 5 / 9; // F2C
}
// Write the result "as we type" in the other ($targ) field:
$targ.value = !isNaN(temp) ? parseFloat(temp.toFixed(1)) : "Err";
// (Above:) temp is a num ? return floated number, else: "Show some error"
}
// Assign input listeners to trigger the above function:
$f.oninput = FC_CF;
$c.oninput = FC_CF;
Celcius: <input id="c">
Fahrenheit: <input id="f">
You can separate the functions which do the temperature conversion as follows i did somw changes in the code.
<p>
<label>Fahrenheit</label>
<input id="outputFahrenheit" type="number" placeholder="Fahrenheit"
oninput="temperatureConverterCelsius(this.value)"
onchange="temperatureConverterCelsius(this.value)" value="">
</p>
<p>Celsius: </p>
<input id="outputCelsius" type="number" placeholder="Celsius"
oninput="temperatureConverterFahrenheit(this.value)"
onchange="temperatureConverterFahrenheit(this.value)" value="">
</p>
<script type=""text/javascript>
function temperatureConverterCelsius(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelsius").value = (valNum-32) / 1.8;
//document.getElementById("outputFahrenheit").value = (valNum*1.8)+32;
}
</script>
</body>
</html>
class Temperature_conversation {
constructor(celsius) {
this.celsius= celsius;
this.fahrenheit= 0;
this.table_begin= -50.0;
this.table_end= 50.0;
this.table_step= 10.0;
console.log('---------------------Conversion--------------------------');
console.log('Celsius fahrenheit');
for(this.celsius = this.table_begin; this.celsius <= this.table_end; this.celsius += this.table_step){
this.fahrenheit = this.celsiusToFahrenhit(celsius);
}
}
celsiusToFahrenhit(c){
const minimun_celsius = -273.15;
if (c < minimun_celsius) {
throw 'O argumento es pequeno';
}
this.celsius = (9.0 / 5.0) * c+ 32;
var res = [this.celsius, this.fahrenheit]
console.table(res);
}
}

Categories