Skip to main content

Posts

Showing posts with the label format number

Javascript form validation

One of the most popular uses of Javascript is when it comes to validating user input on a form. The most hateful way, though, is by not using onsubmit. A number of times I come across code where someone uses an image in place of the submit button and uses the onclick event which will validate then submit the form. Yeauch! Very bad practice! The first thing to do with the form is place the Javascript function in the onsubmit attribute for the form, e.g. <form name="reg" method="post" onsubmit="return validateForm();" The use of return lets the form submit when the function returns true. If the function does not return true (i.e. false) then the form will not submit - as shown below. function validateForm(){ return false; } Getting a reference to the form is the next step. There are a number of ways to do this: document.forms[0] document.forms['reg'] document.getElementById('reg') This will work when id is used on the form Passing an o...

XSL Calculations and Formatting

While using XSL I came across the need to perform a calculation by converting metres to some other units, and then formatting the output. number() takes the value of the selected node and treats it as an actual number.  number() div 1000 is my actual calculation to convert metres to kilometres. Notice that I am using the keyword div and not the / operator as you would with other languages such as Javascript:     <xsl:value-of select="number() div 1000"/> km Being all nice and outputting my desired output, this is flawed. When it comes to outputting in other units such as miles and yards, it shows a large nasty decimal number.  It's far too accurate and long that it's not really user friendly.  A simple presentation would be to limit the output to 2 decimal places.  The answer to this is to use the format-number() function. This was all achieved in this one-liner:     <xsl:value-of select="format-number(number() div 1000,'#0....