Valhalla Legends Archive

Programming => Web Development => Topic started by: Imperceptus on September 29, 2009, 05:41 PM

Title: Javascript Adding Values
Post by: Imperceptus on September 29, 2009, 05:41 PM
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?
Title: Re: Javascript Adding Values
Post by: Maged on September 29, 2009, 06:08 PM
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).
Title: Re: Javascript Adding Values
Post by: Imperceptus on September 29, 2009, 06:12 PM
Thanks Maged, that covered exactly what I needed =).
Title: Re: Javascript Adding Values
Post by: Maged on September 29, 2009, 06:14 PM
Blah, I don't think Number() works on IE. See my edit.
Title: Re: Javascript Adding Values
Post by: Imperceptus on September 30, 2009, 09:45 AM
Does seem to be working with IE 8/Google Chrome/Opera/FF.  Trying to find out what versions of browsers dont like it.