• Welcome to Valhalla Legends Archive.
 

Javascript Adding Values

Started by Imperceptus, September 29, 2009, 05:41 PM

Previous topic - Next topic

Imperceptus

I am trying to add the values from textboxes in a webpage
       function totalfields() {
           var         function totalfields() {
            var total = 0;
            var elements = document.getElementsByTagName("input"); // make a collection of all input elements
            for (var i = 0; i < elements.length; i++)
                if (elements[i].type == "text") {
                    var txtval = elements[i].value;
                    txtval = txtval.replace(/[^\d\.-]/g, '');
                    total += txtval;
            }
            alert(total);       
        }

The popup shows that I am concatenating and not adding, what did I goof on?
Quote from: Hazard on August 07, 2003, 03:15 PM
Highlight your entire code. Press the delete key. Start over again using Cuphead's CSB tutorial and work your way from their rather than raping code from downloaded sources meant purely for learning purposes. If this does not fix the problem, uninstall Visual Basic and get a new hobby. I suggest Cricket.

Maged

#1
You're still adding two strings. You'll want to convert them to a number using parseFloat(string) or parseInt(string) (if you just want an integer).

Imperceptus

Thanks Maged, that covered exactly what I needed =).
Quote from: Hazard on August 07, 2003, 03:15 PM
Highlight your entire code. Press the delete key. Start over again using Cuphead's CSB tutorial and work your way from their rather than raping code from downloaded sources meant purely for learning purposes. If this does not fix the problem, uninstall Visual Basic and get a new hobby. I suggest Cricket.

Maged

Blah, I don't think Number() works on IE. See my edit.

Imperceptus

Does seem to be working with IE 8/Google Chrome/Opera/FF.  Trying to find out what versions of browsers dont like it.
Quote from: Hazard on August 07, 2003, 03:15 PM
Highlight your entire code. Press the delete key. Start over again using Cuphead's CSB tutorial and work your way from their rather than raping code from downloaded sources meant purely for learning purposes. If this does not fix the problem, uninstall Visual Basic and get a new hobby. I suggest Cricket.