Adding floats together with commas and decimal places

Someone contacted me about adding some numbers together with comma’s and dots within there values, here is the email via the contact me page.

“Please I need a javascript code that can enable me add two or more numbers containing dot(.) and/or comma (,) together. For example, 122.34 + 233.56. Or/And 233,239.34 + 323,322.44. Thanks in advance.”

Here is the code that will accomplish the request.

<html>
<script type="text/javascript" >
       function load()
       {
               var value1="233,122.34";
               var value2="233.56";
               alert(parseFloat(value1.replace(",",""))+parseFloat(value2.replace(",","")));
       }
 
</script>
<body onload="load()">
</body>
</html>

The main part is the parseFloat and replacing the “,” with nothing “” to remove the none float characters via the object replace method.

How to convert the output format in Javascript

How to convert the output format in Javascript

If you want to format the output in Javascript, you must realize your codes by yourself because there are no related functions in Javascrip. These days, I got a set of functions written in Javascript to realize the data formatting coded by AJAX WebShop (You can dowonload AJAX WebShop in theire official site:link. Version 3 is recommended). They are very helpful.

Find ‘system.js’ in the directory of AJAX WebShop and you will get these functions below:

function FormatFloat(value,mask)
{
       return BasicFormat(value,mask,'FormatNumber')
}
function FormatDate(varDate, bstrFormat, varDestLocale)
{
       return BasicFormat(varDate,bstrFormat,'FormatDate',varDestLocale);
}
function FormatTime(varTime, bstrFormat, varDestLocale)
{
       return BasicFormat(varTime,bstrFormat,'FormatTime',varDestLocale);
}
function BasicFormat(value,mask,action,param)
{
       var xmlDoc;
       var xslDoc;
       var v='<formats><format><value>'+value+'</value><mask>'+mask+'</mask></format></formats>';
       xmlDoc=parseXML(v);
 
       var x; 
       if(isIE)
              x='<xsl:stylesheet xmlns:xsl="uri:xsl">'
       else
              x='<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">';
       x+='<xsl:template match="/">';
       if(isIE) {
              x+='<xsl:eval>'+action+'('+value+',"'+mask+'"';
              if(param)x+=','+param;
              x+=')</xsl:eval>';
       }
       else
              x+='<xsl:value-of select="format-number('+value+',\''+mask+'\')" />';
 
       x+='</xsl:template></xsl:stylesheet>';
       xslDoc=parseXML(x);
       var s;
       if(isIE)
        s= xmlDoc.transformNode(xslDoc)
       else{
              //for mozilla/netscape 
        var processor = new XSLTProcessor(); 
              processor.importStylesheet(xslDoc);
              var result = processor.transformToFragment(xmlDoc, xmlDoc);
        var xmls = new XMLSerializer(); 
        s = xmls.serializeToString(result);
       }
       return s;
}

On mouse events

Within javascript it is able to reference an HTML object so that if any “on” events happen, for example if an mouse hovers over the HTML object it is called onmouseover event and these events are capable of changing the webpage as well.

To create an process attached to an event, you can either add the code inline to the HTML object like

       <a href="/" title="testing" onmouseover="javascript:this.style.background = 'blue'" onmouseout="javascript:this.style.background = 'white'">First Test </a>

This will change the link object <a> events for when the mouse hovers over the <a> HTML object (onmouseover) and also when the mouse leaves the <a> HTML object (onmouseout).

Also with using the body HTML onload event, it is able to attach an javascript process to any object without doing inline code.

       <body onload="javascript:objload('aid');">

which is attached to any function, in this case I have attached to objload(objectID) function.

Here is the full HTML code

<html>
       <head>
              <script language="javascript">
                     /// can do a window.onload function instead of the body onload
                     window.onload = function()
                     {
                            //objload("aid");
                     }
 
                     // function to alter the object with mouse over events
                     function objload(objID)
                     {
                            // obtain the object of the passed in element ID
                            <span style='color:blue'>var</span> obj = document.getElementById(objID);
                            // <span style='color:blue'>for</span> the object mouse over function (e = event)
                            obj.onmouseover = function(e)
                            {
                                   obj.style.background = 'blue';
                                   obj.style.color = 'white'
                                   return true;
                            }
                            // <span style='color:blue'>for</span> the object mouse out function 
                            obj.onmouseout = function(e)
                            {
                                   obj.style.background = 'white';
                                   obj.style.color = 'blue';
                            }
                     }
              </script>
       </head>
       <!-- can do onload event with the standard html -->
       <body onload="javascript:objload('aid');">
              <a href="/" title="testing" onmouseover="javascript:this.style.background = 'blue'" onmouseout="javascript:this.style.background = 'white'">First Test </a>
              <p>
              <a href="/" title="test" id="aid">Second test</a>
</html>

Styles – alter with javascript

To alter style values within a html page via Javascript can be done two different ways, that I know of, one is via getting the object itself and then altering the style from that and the other is via the document style sheets object.

The document style sheets object is all of the styles on the web page and is index within an array manor. For example

       styleSheet = document.styleSheets[<insert number of object>]

But since the two main browsers (Internet Explorer and also Firefox) deal with the css rules within this object with a different reference (IE = rules and FF = cssRules).

       if (styleSheet.cssRules)
              cssRule = styleSheet.cssRules[0]; // Firefox
       else if (styleSheet.rules)
              cssRule = styleSheet.rules[0];         // IE

The other method is via the id of the object, to obtain this just need to use the javascript getElementById function with the document object.

       cssRule = document.getElementById(style)

And then once the object of the style is obtained with both functions can just alter the style of the object with the same code.

       if (cssRule.style.backgroundColor == colour)
              cssRule.style.backgroundColor = colour2;
       else
              cssRule.style.backgroundColor = colour;

Here is the full code

<html>
       <head>
              <style language="text/css">
                     h1 { background-color: lightblue;}
                     #pstyle { background-color : lightblue;}
              </style>       
              <script language="javascript">
                     function alterh1(colour, colour2)
                     {       
                            var styleSheet, cssRule;
                            if (document.styleSheets)
                            {
                                   styleSheet = document.styleSheets[0];
                                   if (styleSheet)
                                   {
                                          if (styleSheet.cssRules)
                                                 cssRule = styleSheet.cssRules[0]; // Firefox
                                          else if (styleSheet.rules)
                                                 cssRule = styleSheet.rules[0];         // IE
                                          if (cssRule)
                                          {
                                                 if (cssRule.style.backgroundColor == colour)
                                                        cssRule.style.backgroundColor = colour2;
                                                 else
                                                        cssRule.style.backgroundColor = colour;
                                          }
                                   }
                            }
                     }
 
                     function alterstyle(style,colour, colour2)
                     {
                            var cssRule;
                            cssRule = document.getElementById(style);
                            if (cssRule)
                            {
                                   if (cssRule.style.backgroundColor == colour)
                                          cssRule.style.backgroundColor = colour2;
                                   else
                                          cssRule.style.backgroundColor = colour;
                            }
                     }
              </script>
 
       </head>
       <body>
              <h1>Change this style</h1>
              <input type="submit" value="click here" onclick="javascript:alterh1('blue', 'lightblue')"/>
 
              <p id="pstyle">
                     HI there
 
              <input type="submit" value="click here" onclick="javascript:alterstyle('pstyle','blue','lightblue')"/>       
       </body>
 
</html>

Arrays – Insert into a div

Javascript arrays are just like any other object orientated language, in the aspect an array is a block of memory associated with main object. To create an array in Javascript just need to call
= Array(5);
Or
= Array(‘value1′,’value2’);

The code below is using a default screen from which you press the ‘Click Here’ button and the array is used to insert into a <div> html tag. To insert into a div tag within javascript, there needs to be a new node created and in this instance a text node is created which in turn is appended to the div.

The code hopefully will explain more.

<html>
       <script language="javascript">
              // setup the main array
              var setArray = Array("hi", "there", "this", "is", "a","test");
 
              // insert the array into the DIV smalltest object
              function insertArray()
              {
                     var theText = "";  // set the theText output to an empty string otherwise it would start with null.
                     for (var i=0; i < setArray.length; i++)
                     {
                            // create the array of text to insert
                            theText += setArray[i];
                     }
                     // create the createTextNode 
                     var insertText = document.createTextNode(theText);
                     document.getElementById("smalltest").appendChild(insertText);
              }
       </script>
       <body>
              Just a small test, 
              <div id="smalltest">
              </div>
              <input type="submit" value="click here" onclick="javascript:insertArray()" />
       </body>
</html>

Add two numbers

This tutorial demonstrates how to get two inputs from the user within a HTML page and have a button on the page to call a javascript method to process the inputs and alter the answer output on the web-page.

Within HTML, there are input tags that allow the user to input data that is passed either to a javascript method to validate the inputs (for example a registration forum) or to pass data back to the server (after the validation has taken place if required).

The value 1 input is defined as
value 1 = <input type=’text’ id=value1 name=’value1′ value=’1’/>
the input type is text, which means any textual value, [A-Z]*[0-9]* but in this case since just adding integers [0-9] would be the required input.
The id is for getting the value from the input with using javascript document.getElementById, value is for setting the default value.

The function within the javascript, addNumbers() will get the inserted value1 by using the javascript document object. Within this object there is a method called getElementById that returns back the object, which in turn using the .value of the object returned can be passed to the parseInt (which converts a string value into a integer value). The same method is used for the answer input within the web-page (getElementById) but assign the return object to a variable allows access to the .value to set the value on the web-page.

The source code is

<html>
  <head>
        <title>Input tutorial</title>
        <script language="javascript">
                function addNumbers()
                {
                        var val1 = parseInt(document.getElementById("value1").value);
                        var val2 = parseInt(document.getElementById("value2").value);
                        var ansD = document.getElementById("answer");
                        ansD.value = val1 + val2;
                }
        </script>
  </head>
  <body>
        value1 = <input type="text" id="value1" name="value1" value="1"/>
        value2 = <input type="text" id="value2" name="value2" value="2"/>
        <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
        Answer = <input type="text" id="answer" name="answer" value=""/>
  </body>
</html>

save as addtwonumbers.html and then open in a web browser (e.g. FireFox)

Hello world

Well, this is the javascript hello world. The javascript is used within web pages and the client browser (e.g. Internet Explorer or Firefox etc) will use the javascript code to help display the content of the page. This tutorial displays the “Hello World” in the webpage.

If you cut from

<html>
       <title>Javascript hello world</title>
       <body>
       <script language="javascript">
              document.write("Hello World!");
       </script>
       </body>
</html>

as javascripthelloworld.html

and then open up within IE or FF, this shall display a white page with the words in the top left “Hello World!”

The javascript is based on Objects, the same as Java,C++, C# etc, and the document object is the web page itself.

Hope it helps