Reputation: 145
I have to make a calculation with Celsius (C) and Fahrenheit (F), and I think the form action line is wrong. How can I fix it?
Here is my HTML:
<form action="javascript.html">
Convert Celsius to Fahrenheit:<br>
<input type="text" name="converterCtoF"><br>
<input type="submit" value="Submit">
</form>
Here is my JavaScript code:
function tempertureConverter(C) {
return (9/5)*C + 32;
}
What about the other way as well? Converting F to C.
Upvotes: 2
Views: 11490
Reputation: 182
You would not change a PHP script. You need to create one. In this example above ...
<form action="celsius.php" method="get">
Convert Celsius to Fahrenheit:<br>
<input type="text" name="converterCtoF"><br>
<input type="submit" value="Submit">
</form>
You need to create a file named celcius.php and add something similar to:
<?php
$c = $_GET['converterCtoF'];
$f = convertTemp(c);
echo(f);
function convertTemp(temp) {
return (9/5)*C + 32;
}
?>
Upvotes: 0
Reputation: 7715
Is this jfiddle what you had in mind? It listens for the form submission and calculates the Fahrenheit from the Celsius text field. This would all be on one page.
HTML:
<form name="temperature_form" action="">
Convert Celsius to Fahrenheit:<br>
<input type="text" name="converterCtoF" id="converterCtoF"><br>
<input type="submit" value="Submit">
</form>
JavaScript:
document.forms["temperature_form"].onsubmit = function(){
var c = document.getElementById("converterCtoF").value;
var f = (9/5)*c + 32;
alert(f);
return false;
}
Upvotes: 2
Reputation: 10496
I think you want to set the form action to your PHP script, not JavaScript.
<form action="celsius.php" method="get">
Convert Celsius to Fahrenheit:<br>
<input type="text" name="converterCtoF"><br>
<input type="submit" value="Submit">
</form>
Then in celsius.php you can access to the text field value via $_GET['converterCtoF'].
Upvotes: 0
Reputation: 36648
You should be posting to a different file with your form, but since you didn't specify the mark-up for the page you are posting to, here is a solution that will display the Fahrenheit on the current page.
<script>
function tempertureConverter(){
var C = document.getElementById("degree").value;
alert((9/5)*C+32);
}
</script>
<form>
Convert Celsius to Fahrenheit:<br>
<input type="text" name="converterCtoF" id = "degree"><br>
<input type="button" value="Submit" id = "submit"
onClick = "tempertureConverter()">
</form>
The above grabs the Celsius value the user inputs and runs the conversion function on it. The result is then displayed as a pop-up in the browser.
A working example is here.
Upvotes: 3