DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore

Putting a javascript calculation result into HTML form automatically

StackOverflow https://stackoverflow.com/questions/20301797
 Checked

Question

I have a javascript function that calculates an integer sum of some variables. It's basically

fscalculate() = number1 + number2 + number3 = totalScore

where fscalculate() adds three numbers and sets the result as the variable totalScore.

I have created a form that asks the user for his name and email, I have used a php script to send the name and email to an email address using the POST method.

What I would like is to create a field that is automatically populated with the integer totalScore. If this is possible then I should be able to add a line to my php script to send this with the user name and email address,

Any help would be most appreciated!

No correct solution

OTHER TIPS

Use the HTML5 <output> Tag. It's designed for capturing form calculation results.

<form oninput="totalScore.value = (+num1.value)+(+num2.value)+(+num3.value);">
    <input type="number" id="num1" />+
    <input type="number" id="num2" />+
    <input type="number" id="num3" />=
    <output name="totalScore" for="num1 num2 num3"></output>
</form>

Here's a breakdown of what's happening:

  • Since the input is a string, we want to coerce it into a number using +someString

  • We specify the list of input IDs of fields that go into the calculation. Typically, this is used so that we don't get NaN result in case one of the input fields is empty. But since we're coercing the input into a number, an empty string is converted to 0. Hence, it's not necessary, but good to have for clarity (especially if the calculations get more complex).

  • Note that we don't include name attributes for the number inputs. This is to prevent them from getting submitted. We're only concerned about the result.

Also, here's a list of browsers that currently support output.

var totalscore = num1+num2+num3;

Assuming your html form element is

<input type="text" id="score"> 

use jquery

$("#score").val( "hi");

complete test code:

<html>
<head>
<script src="jquery.js">
</script>
<script>
$(document).ready(function(){
$("#score").val( "hi");
});
</script>
</head>
<body>
<input type="text" id="score">
</bodY>
</html>

Try something like this:

<input type="text" id="total" value="" disabled />
<script>
    var totalScore = num1+num2+num3;
    document.getElementById("total").value = totalScore;
</script>

Good Luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow