Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q131 How do I add form elements together, I have tried many different ways but I always either get NaN or a concenated string (ie 15 + 16 + 1 + 52 = 1615152 != 84)?

You are here: irt.org | FAQ | JavaScript | Form | 6 | Q131 [ previous next ]

Try

<form>
<input type="text" name="field1" value="15">
<input type="text" name="field2" value="16">
<input type="text" name="field3" value="1">
<input type="text" name="field4" value="52">
<input type="button" value="Sum" onClick="sum(this.form)">
</form>

<script language="JavaScript"><!--
function sum(objRef) {
  var result = 0;
  result =+ objRef.field1.value - 0;
  result =+ objRef.field2.value - 0;
  result =+ objRef.field3.value - 0;
  result =+ objRef.field4.value - 0;
  alert(result);
}
//--></script>

Ray Pooley writes:

Use parseInt() or parseFloat() methods to assign the form text variables to numeric variables and perform your maths on the new variables. eg: numvar = parseFloat(formelementvalue); If formelementvalue contains '30.1' then numvar will be equal to 30.1 numeric.

Feedback on 'Q131 How do I add form elements together, I have tried many different ways but I always either get NaN or a concenated string (ie 15 + 16 + 1 + 52 = 1615152 != 84)?'

©2018 Martin Webb