Valhalla Legends Forums Archive | Web Development | Javascript Adding Values

AuthorMessageTime
Imperceptus
I am trying to add the values from textboxes in a webpage
[code]        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);     
        }[/code]
The popup shows that I am concatenating and not adding, what did I goof on?
September 29, 2009, 10:41 PM
Maged
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).
September 29, 2009, 11:08 PM
Imperceptus
Thanks Maged, that covered exactly what I needed =).
September 29, 2009, 11:12 PM
Maged
Blah, I don't think Number() works on IE. See my edit.
September 29, 2009, 11:14 PM
Imperceptus
Does seem to be working with IE 8/Google Chrome/Opera/FF.  Trying to find out what versions of browsers dont like it.
September 30, 2009, 2:45 PM

Search