Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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)?

irt.org | Knowledge Base | JavaScript | Form 6 | Q131 [ previous next ]

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)?

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)?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.