SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
-
Jun 12, 2008, 12:39 #1
- Join Date
- Dec 2005
- Posts
- 964
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Adding numbers from 2 or more textfileds into a textfiled?!?!
I have tryid to search the net for a good tutorial or script for this but with no luck :-(.
I want to dynamicly add numbers inserted in 2 or more textfields into another textfield. Can somebody guide me in the right direction in terms of tutorials or scripts...
Thanks
-
Jun 12, 2008, 14:14 #2
- Join Date
- Jan 2004
- Location
- LA, California
- Posts
- 123
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Sample HTML code with 5 text fields, a button and one field for the result
HTML Code:<input type="text" name="t1" id="t1" /><br /> <input type="text" name="t2" id="t2" /><br /> <input type="text" name="t3" id="t3" /><br /> <input type="text" name="t4" id="t4" /><br /> <input type="text" name="t5" id="t5" /><br /> <input type="button" value="add" id="add" /> <input type="text" name="result" id="result" />
Code javascript:<script type="text/javascript"> // attach click listener document.getElementById('add').onclick = function() { // IDs of the text fields you want to add var addthese = ['t1', 't2', 't3', 't4', 't5']; var result = 0; // end result var tmp = 0; // the next number for (var i = 0; i < addthese.length; i++){ // get the number value of the next field tmp = parseInt(document.getElementById(addthese[i]).value, 10); if (isNaN(tmp)) { // make it 0 if it's not a valid number tmp = 0; } result += tmp; // add to the running sum } // update the result field document.getElementById('result').value = result; } </script>
-
Jun 12, 2008, 14:34 #3
- Join Date
- Dec 2005
- Posts
- 964
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Thanks... Does this do in realtime? I think is something like onChange???
-
Jun 13, 2008, 07:15 #4
- Join Date
- Nov 2004
- Location
- Nelson BC
- Posts
- 2,310
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
For onchange:
Code:<script type="text/javascript"> // IDs of the text fields you want to add var addthese = ['t1', 't2', 't3', 't4', 't5']; function addEm() { var result = 0; // end result var tmp = 0; // the next number for (var i = 0; i < addthese.length; i++){ // get the number value of the next field tmp = parseInt(document.getElementById(addthese[i]).value, 10); if (isNaN(tmp)) { // make it 0 if it's not a valid number tmp = 0; } result += tmp; // add to the running sum } // update the result field document.getElementById('result').value = result; } // attach click listener document.getElementById('add').onclick = addEm; // attach onchange listener for (var i=0; i < addthese.length; i++) { document.getElementById(addthese[i]).onchange = addEm; } </script>
Bookmarks