Pulling value of user input into function and invoking function on call - javascript

function toCelsius(f) {
return (5 / 9) * ('temperature' - 32);
}
<h2>JavaScript Functions</h2>
<p>This example calls a function to convert from Fahrenheit to Celsius:</p>
<br> Enter Temperature <br>
<input type="number" name="temperature" "temperature"> <br><br>
<button type="button" onclick="toCelsius(f)"> Translate </button>
Using JS, what I want to accomplish is to be able to pull the number that the user inputs into the 'temperature' input into the 'toCelsius' function and then on click of the button invoke 'toCelsius'.
The end objective is for a user to be able to input a temperature in farenheit then translate it to celsius

You cannot pass (f) - instead read it in the function
You need to show the result - here I use a span
JS Math can create funny decimals. I use toFixed to get rid of them. You can add a number - toFixed(2) to show how many decimals you want
You can also use Math.round or Math.floor to round down
function toCelsius() {
var f = document.getElementById("temperature").value || 0; // Zero if nothing
document.getElementById("result").innerHTML=((5 / 9) * (f - 32)).toFixed();
}
<h2>JavaScript Functions</h2>
<p>This example calls a function to convert from Fahrenheit to Celsius:</p>
Enter Temperature <br>
<input type="number" name="temperature" id="temperature"> <br><br>
<button type="button" onclick="toCelsius()"> Translate </button><br/>
Result: <span id="result"></span>°C

One way to pull (get) the value of the input is by using jquery or the DOM.
document.getElementByName('temperature').value
and
$("#temperature").val()
are ways to access the input.

Related

The code i have written doesnt show results on input percentage

Hi im trying to calculate the percentage of 2 inputs but its not showing results can anyone tell me whats the problem
var Shots = document.getElementById("shots").value;
var Makes = document.getElementById("makes").value;
var results = (Makes / Shots) * 100;
function perqindja() {
document.getElementById("answer").innerHTML = results;
};
<h2>Calculate your shots</h2>
<p>Type the number of shots taken:</p>
<input type="number" name="Shots" id="shots">
<p>Type the number of shots made:</p>
<input type="number" name="Makes" id="makes">
<button onclick="Calculate()">Calculate</button>
<p>The shot percentage:<span id="answer"></span></p>
You should define the variable inside the function so that it could store the input value after user click the button. Also, you doesn't define the Calculate(). I remove the perqindja() since I don't find it user in the code.
function Calculate() {
var Shots = document.getElementById("shots").value;
var Makes = document.getElementById("makes").value;
var results = (Makes / Shots) * 100;
document.getElementById("answer").innerHTML = results;
};
<p>Type the number of shots taken:</p>
<input type="number" name="Shots" id="shots">
<p>Type the number of shots made:</p>
<input type="number" name="Makes" id="makes">
<button onclick="Calculate()">Calculate</button>
<p>The shot percentage:<span id="answer"></span></p>
The first problem is that the function Calculate is not defined.
By the way, in javascript it is a good practice to give function lower case names.
Second, you need to pass values to the calculate function.
Everything should work once you fix these 2 issues.
Your functions name is ‘perqindja()’ but you try to call ‘ Calculate()’ function on click in your html

How can I round a number to the nearest hundredth using vanilla JavaScript?

For example, if I entered the number 2.5 into an input field and wanted to turn it into 0.025, would I use Math.round() or some other way?
My goal is to take the decimal number entered into the input field and store the hundredth of that number into a variable in JS.
Here's what I've got so far:
function calculator() {
const hundredthNumber = document.getElementById('numberInput').getElementByTagName('input').value;
}
<div class="inputSection" id="numberInput">
<h3>What is your number?</h3>
<input type="number" placeholder="">
</div>
You can Use this Code :
function roundoff(x)
{
return Number.parseFloat(x).toFixed(2)/100;
}
console.log(roundoff(2.5));

Javascript: Average of 2 user input values

I apologize for the basic question but I have been trying to make this work for a long time and I just can't seem to get this code to return a value.
I am embarrassed to admit how long I have been attempting to make it work, and how many StackOverflow questions that were related that I have looked at, however, none were as simple as my code, and when I attempted to make something closer to how mine looked, it just wouldn't alert anything.
The idea is the following:
User inputs 2 numbers,
clicks the button,
and is alerted the average of the numbers they input.
My alert has been NaN no matter how many iterations I have made. I could really use some advice. Thanks in advance!
<html>
<head>
<title> Javascript </title>
<body>
<p> Enter two number for an average below </p>
<p> Number 1<input type="text" id="userInput1"></input></p>
<p> Number 2<input type="text" id="userInput2"></input></p>
<button id="averageButton"> Calculate</button>
<script type="text/javascript">
function average(a, b) {
return ((a + b) /2);
}
document.getElementById("averageButton").onclick = function (){
var a = document.getElementById("userInput1").value;
var b = document.getElementById("userInput2").value;
alert(average());
}
</script>
</body>
</html>
You failed to pass the numbers a,b to your function - a simple mistake.
But since the inputs are seen as strings you also need to convert them to numbers a*1
See commented code
<html>
<head>
<title> Javascript </title>
<body>
<p> Enter two number for an average below </p>
<p> Number 1<input type="text" id="userInput1"></input></p>
<p> Number 2<input type="text" id="userInput2"></input></p>
<button id="averageButton"> Calculate</button>
<script type="text/javascript">
function average(a, b) {
// force the input as numbers *1
return ((a*1 + b*1) /2);
}
document.getElementById("averageButton").onclick = function (){
var a = document.getElementById("userInput1").value;
var b = document.getElementById("userInput2").value;
// pass the numbers to the average function!
alert(average(a,b));
}
</script>
</body>
</html>
At first glance you might need to convert your input values from strings to floats and actually pass them to the average function.
You may want to change the inputs to
<input type="number"> to prevent users from adding non-numeric values.
Secondly parse your inputs as document....value returns string,
var a = parseFloat(document.getElementById("userInput1").value);
var b = parseFloat(document.getElementById("userInput2").value);
If you do just this you wouldn't have to deal into the funny business of doing a*1.
// force the input as numbers *1
return ((a*1 + b*1) /2);
This block isn't required since multiplying a string with a number returns a NaN value.
function average(a, b) {
return ((a + b) / 2);
}
document.getElementById("averageButton").onclick = function() {
var a = document.getElementById("userInput1").value;
var b = document.getElementById("userInput2").value;
alert(average());
}
<p> Enter two number for an average below </p>
<p> Number 1<input type="text" id="userInput1"></input>
</p>
<p> Number 2<input type="text" id="userInput2"></input>
</p>
<button id="averageButton"> Calculate</button>

How do I execute a JavaScript function from clicking an HTML button?

I am trying to write a short piece of html code that, given two initial amounts, attempts to find the number greater than or equal to the first that wholly divides the second given amount. The code tries to divide the numbers, and if it is unsuccessful, adds 1 to the first number and tries to divide again, etc...
I want the code to return the value that does wholly divide the second number AND the answer to the division (with some plain text appearing around it).
Added to this, or at least I'd like there to be, is that upon clicking one of 5 different buttons a multiplication operation is performed on the first given number, it is rounded up to the nearest whole number, and THEN the function attempts to divide this into the second given number.
It's difficult to explain exactly what I want without showing you the code I have so far, so here it is:
<html>
<head>
<b>Rounded Commodity Pricing:</b><br>
<script language="Javascript">
function finddivid(marketprice,tradevalue) {
var KWDex = 0.281955
var GBPex = 0.625907
var USDex = 1
var CADex = 0.998727
var EURex = 0.784594
if
(currency == "KWD")
var currencyMarketprice = Math.ceil(marketprice*KWDex)
else if
(currency == "GBP")
var currencyMarketprice = Math.ceil(marketprice*GBPex)
else if
(currency == "USD")
var currencyMarketprice = Math.ceil(marketprice*USDex)
else if
(currency == "CAD")
var currencyMarketprice = Math.ceil(marketprice*CADex)
else if
(currency == "EUR")
var currencyMarketprice = Math.ceil(marketprice*EURex)
if (tradevalue % currencyMarketprice == 0)
return ("tonnage = " + tradevalue / currencyMarketprice + " mt, and price = " + currencyMarketprice +" " +currency +" per mt");
else
{for (var counter = currencyMarketprice+1; counter<(currencyMarketprice*2); counter++) {
if (tradevalue % counter == 0)
return ("tonnage = " + tradevalue / counter + " mt, and price = " + counter +" " +currency +" per mt");}}};
</script>
</head>
<p>Select currency:
<input type="button" value="KWD" OnClick="var currency = KWD">
<input type="button" value="USD" OnClick="var currency = USD">
<input type="button" value="GBP" OnClick="var currency = GBP">
<input type="button" value="EUR" OnClick="var currency = EUR">
<input type="button" value="CAD" OnClick="var currency = CAD">
<P>Enter today's price of commodity in USD: <input name="mktprc" input type="number"><br><p>
<P>Enter value of trade: <input name="trdval" input type="number">
<input type="button" value="Calculate" OnClick="showMeArea.value=finddivid(mktprc,trdval);">
<p>
<br><br>
<input name="showMeArea" readonly="true" size="30">
</html>
If you run this html in your browser you should see what I am trying to achieve.
It is far from complete but here are the main problems/features that I need help with:
I would like to be able to click on one of the 'currency' buttons so that upon clicking, the variable 'currency' is assigned and then used in the function finddivid.
(2. This isn't as important right now, but eventually, once this is working, I'd like it so that upon clicking one of the currency buttons, it changes colour, or is highlighted or something so that the user knows which currency rate they are using.)
Upon entering the numbers into the two boxes I would like to click 'Calculate' and have it return what I've written in the function into the 'showMeArea' read-only box at the end of the code.
I know I'm probably missing loads of stuff and I might be miles away from success but I am very new to programming (started 4 days ago!) so would like any like of help that can be offered.
Thanks in advance of your comments.
The first request requires that you put the currency into the actual script, and I would recommend using a setter function:
<script language="Javascript">
var currency; // you might want to set this at a default just in case
function setCurrency(val) { currency = val; } // Setter function
function finddivid(marketprice,tradevalue) {
Then call it in your button click:
<input type="button" value="KWD" onClick="setCurrency('KWD');">
As for the second request, I'd say you have the concept down well enough, but you don't have the method exactly right. First your inputs will need an id attribute:
<input name="mktprc" id="mktprc" input type="number">
<input name="trdval" id="trdval" input type="number">
The name attribute is used for posting values, the id attribute is used by javascript to find elements within a page. Using jQuery would make retrieving these elements easy, but I'll show both the jQuery and the standard JavaScript method of doing this:
jQuery:
<input type="button" value="Calculate" OnClick="$('#showMeArea').val(finddivid($('#mktprc'),$(#'trdval')));">
The $('#id') selects an element. The method .val() sets the value.
Note for the jQuery purists: Yes, there are much better/sophisticated ways to accomplish this with jQuery, but this answer is targeted to my perception of OP's JavaScript capability.
Standard Javascript:
<input type="button" value="Calculate" OnClick="document.getElementById('showMeArea').value = finddivid(document.getElementById('mktprc'),document.getElementById('trdval'));">

javascript calculator to decimal places and images as button

i have a small javascript form
<div id="calculator-text"><h2>Tape calculator - based on cable size 1 mm to 28 mm, with 15% overlap</h2></div>
<form name="form1" method="post" action="">
<div id="calcformlabel"><label for="val2">Enter your cable size</label> (in mm)</div>
<div id="calcformtext1"><input type="text" name="val2" id="val2"></div>
<div id="calcformbutton"><input type="button" name="calculate" id="calculate" value="Calculate"></div>
<div id="calcformresult">The tape size you require is:- <span id="result1" class="maintext1"></span> (mm)</div>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
// get the input values
var val2 = parseInt(document.getElementById('val2').value);
// get the elements to hold the results
var result1 = document.getElementById('result1');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message
// to the array if it's not a number
if (isNaN(val2)) {
msg.push('<span class="maintext1">Enter your cable size</span>');
}
// if the array contains any values, display the error message(s)
// as a comma-separated string in the first <span> element
if (msg.length > 0) {
result1.innerHTML = msg.join(', ');
} else {
// otherwise display the results in the <span> elements
result1.innerHTML = val2 * 3.142 * 1.15;
}
};
</script>
basically this is a simple calculation
a) how can i get this to output to 2 decimal places (and obviously round up or down depending on -.5 = round down and +.5 = round up)
b) replace the input type button for an image ( i have tried the obvious code and >input type = image>, basically these do actually work but instead of displaying the actual result, they display the result in a split second then reload the page with the blank form again...
any help on this would be much appreaciated
thanks in advance
for a part of your question
you can round javascript to specific precision by
Link :Number rounding in JavaScript
var original=28.453
1) //round "original" to two decimals
var result=Math.round(original*100)/100 //returns 28.45
2) // round "original" to 1 decimal
var result=Math.round(original*10)/10 //returns 28.5
3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000 //returns 8.111
The .toFixed() method lets you round off to n decimal places, so:
result1.innerHTML = (val2 * 3.142 * 1.15).toFixed(2);
I think the problem you're having with the image is that <input type="image"> defines the image as a submit button. Perhaps just include a standard image with an <img> tag rather than <input type="image">. If you give it an id='calculate' it should still work with your existing JS.
Or you could use a button element containing an img element so that you can specify the type (as not being submit):
<button type="button" id="calculate"><img src="yourimage"></button>
(I'm not sure that you need a form at all for this functionality since you don't seem to want to submit anything back to the server.)
To swap the button for an image, replace the button <input> with this code:
<img src="http://www.raiseakitten.com/wp-content/uploads/2012/03/kitten.jpg" name="calculate" id="calculate" value="Calculate" onclick="document.forms['form1'].submit();" />
It adds the image and a submit function for your form.
To round to two decimal places, use this function:
function twoDP(x){
return Math.round(x*100)/100
}
use it like this:
twoDP(100/3) //returns 33.33
it might also be relevant for you to use Math.PI
var result = val2 * Math.PI * 1.15 ;

Categories

Resources