BlueShark
BlueShark

Reputation: 148

how to get the value of a function from a button click in javascript?

i am new to javascript and am trying to go through tutorials to understand the concepts.

this is my function

function toCelsius(fahrenheit){

    (5/9) * (fahrenheit-32);    
    document.getElementById("demoTemp").onclick.toString();

}

and i am trying to invoke it here:

<form>
<br>
Enter number: <input type="text" name="firstname">

<!-- <input type="text" name="lastname"> -->
<button type="button" onclick="toCelsius()"> new temp in Celsius </button>
</form>

<p id="demoTemp"></p>

i want the user to be able to enter a value and then hit the button that will tell them their new temperature from fahrenheit to celsius

Upvotes: 0

Views: 68

Answers (3)

Pankaj Goyal
Pankaj Goyal

Reputation: 1548

You do not need to pass anything in the function. Try this JS :-

function toCelsius(){
    var fahrenheit = document.getElementsByName("firstname")[0].value;
    var cel = (5 / 9) * (fahrenheit - 32);    
    document.getElementById("demoTemp").innerHTML = cel;
}

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59252

Just put the result in the inner html.

function toCelsius(){
    var fahrenheit = document.getElementsByName("firstname")[0].value;
    var cel = (5 / 9) * (fahrenheit - 32);    
    document.getElementById("demoTemp").innerHTML = cel;
}

Upvotes: 4

Prakhar Asthana
Prakhar Asthana

Reputation: 91

You should make your function in this way :

  function toCelsius(){    var fahrenheit = document.getElementById('firstname').value; var cel=     (5/9) * (fahrenheit -32);        document.getElementById("demoTemp").innerHTML = cel;}

Upvotes: 0

Related Questions