vicarus99
vicarus99

Reputation: 59

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

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

Upvotes: 3

Views: 450

Answers (2)

Victor Wei
Victor Wei

Reputation: 359

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.

Upvotes: 1

mplungjan
mplungjan

Reputation: 178403

  1. You cannot pass (f) - instead read it in the function
  2. You need to show the result - here I use a span
  3. 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
  4. 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

Upvotes: 4

Related Questions