Showing posts with label html. Show all posts
Showing posts with label html. Show all posts

Wednesday, December 3, 2014

Show Resultset as HTML table

There are times you simply want to show some result set as a table on the screen.
You do not need anything fancy, just show some tabular data on the screen.

In order to solve this issue I wrote a very small and lightweight Java class named: ResultSetToHtmlTable. Even through this class is doing a quite simple task it still have some nice qualities:

  • It is very fast. It doesn't construct any string. It simply writes the table directly to a writer.
  • It doesn't use any external libraries. All plain and simple Java.
  • It is only a single class.
  • It knows to format the data in each column. It supports the following formats:
    • Integer - Show 1000 as 1,000
    • Float - Show 0.5145235 as 0.51
    • Currency - Show 5.2 as $5.2
    • Percentage - Show 0.5 as 50%
    • Date - Show 12/5/2014 as 5 Dec 2014
    • Date and time - Show 12/5/2014 12:00:00 as 5 Dec 2014 12:00:00
    • Time - Show only the time part of a date. For example: 13:22:15
  • It allows to align the data to the left or right and add titles to columns.
  • If no strict column information is supplied is knows to auto detect:
    • Column types.
    • Column titles - titles are named as column names returned in query.
    • Column alignment - Numbers are aligned to the right.
The code of this class is quite simple and straightforward. Here is how it looks like:
package com.todacell.util.sql;

import java.io.IOException;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.text.DateFormat;
import java.text.Format;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Bashan
 *         Date: 18/11/2014 15:07
 */
public class ResultSetToHtmlTable {

  public void writeTable(ResultSet rs, Writer writer, Column[] columns) throws IOException, SQLException {
    writer.write("<table>");
    // Write titles
    writer.write("\t<tr>\n");
    for (Column column : columns) {
      writer.write("\t\t<th>" + column.title + "</th>");
    }
    writer.write("\t</tr>\n");

    // Write data
    int cols = columns.length;
    while (rs.next()) {
      writer.write("\t<tr>\n");
      for (int i = 0; i < cols; i++) {
        ColumnType columnType = columns[i].columnType;
        String columnAlign = columnAlignToColumnCss.get(columns[i].columnAlign);
        writer.write("\t\t<td" + columnAlign + ">" + format(columnType, rs.getObject(i + 1)) + "</td>");
      }
      writer.write("\t</tr>");
    }

    writer.write("</table>");
  }

  private static Map<Integer, ColumnType> sqlTypeToColumnType = new HashMap<Integer, ColumnType>();
  private static Map<ColumnType, ColumnAlign> columnTypeTpColumnAlign = new HashMap<ColumnType, ColumnAlign>();
  private static Map<ColumnAlign, String> columnAlignToColumnCss = new HashMap<ColumnAlign, String>();

  static {
    // Map SQL types to column types

    // integer
    sqlTypeToColumnType.put(Types.INTEGER, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.BIGINT, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.SMALLINT, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.TINYINT, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.NUMERIC, ColumnType.INTEGER);

    // float
    sqlTypeToColumnType.put(Types.FLOAT, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.DOUBLE, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.DECIMAL, ColumnType.INTEGER);

    // date
    sqlTypeToColumnType.put(Types.TIME, ColumnType.DATE);
    sqlTypeToColumnType.put(Types.TIMESTAMP, ColumnType.DATE);

    // Map column type to column alignment
    columnTypeTpColumnAlign.put(ColumnType.INTEGER, ColumnAlign.RIGHT);
    columnTypeTpColumnAlign.put(ColumnType.FLOAT, ColumnAlign.RIGHT);
    columnTypeTpColumnAlign.put(ColumnType.CURRENCY, ColumnAlign.RIGHT);
    columnTypeTpColumnAlign.put(ColumnType.DATE, ColumnAlign.LEFT);
    columnTypeTpColumnAlign.put(ColumnType.STRING, ColumnAlign.LEFT);

    // Map column alignment to css style
    columnAlignToColumnCss.put(ColumnAlign.LEFT, "");
    columnAlignToColumnCss.put(ColumnAlign.RIGHT, " style=\"text-align:right\"");
    columnAlignToColumnCss.put(ColumnAlign.CENTER, " style=\"text-align:center\"");
  }

  public void writeTable(ResultSet rs, Writer writer) throws IOException, SQLException {
    ResultSetMetaData meta = rs.getMetaData();
    int cols = meta.getColumnCount();

    Column[] columns = new Column[meta.getColumnCount()];
    for (int i = 0; i < cols; i++) {
      ColumnType columnType = sqlTypeToColumnType.get(meta.getColumnType(i + 1));
      ColumnAlign columnAlign = columnTypeTpColumnAlign.get(columnType);
      columns[i] = new Column(
          columnType != null ? columnType : ColumnType.STRING,
          meta.getColumnName(i + 1),
          columnAlign != null ? columnAlign : ColumnAlign.LEFT);
    }

    writeTable(rs, writer, columns);
  }

  public enum ColumnType {
    STRING, INTEGER, FLOAT, DATE, DATE_TIME, TIME, CURRENCY, PERCENTAGE
  }

  public enum ColumnAlign {
    LEFT, RIGHT, CENTER
  }

  private static NumberFormat integerFormat = NumberFormat.getInstance();
  private static NumberFormat floatFormat = NumberFormat.getInstance();
  private static final NumberFormat percentFormat = NumberFormat.getPercentInstance();
  private static final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
  private static final DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
  private static final DateFormat dateTimeFormat = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");
  private static final DateFormat timeFormat = new SimpleDateFormat("hh:mm:ss");

  static {
    floatFormat.setMaximumFractionDigits(2);
    integerFormat.setMaximumFractionDigits(0);
  }

  public String format(ColumnType columnType, Object value) {
    String result;
    if (value != null) {
      if (columnType == ColumnType.STRING) {
        result = value.toString();
      } else {
        Format format;
        if (columnType == ColumnType.FLOAT) {
          format = floatFormat;
        } else if (columnType == ColumnType.CURRENCY) {
          format = currencyFormat;
        } else if (columnType == ColumnType.PERCENTAGE) {
          format = percentFormat;
        } else if (columnType == ColumnType.DATE) {
          format = dateFormat;
        } else if (columnType == ColumnType.DATE_TIME) {
          format = dateTimeFormat;
        } else if (columnType == ColumnType.TIME) {
          format = timeFormat;
        }else {
          format = integerFormat;
        }

        result = format.format(value);
      }
    } else {
      result = "N/A";
    }

    return result;
  }

  public static class Column {
    ColumnType columnType;
    String title;
    ColumnAlign columnAlign;

    public Column(ColumnType columnType, String title, ColumnAlign columnAlign) {
      this.columnType = columnType;
      this.title = title;
      this.columnAlign = columnAlign;
    }
  }
}

And here is a simple example of how to use this code in a JSP file:
 <%@ page import="com.todacell.management.SessionSingleton" %>  
 <%@ page import="com.todacell.util.sql.ResultSetToHtmlTable" %>  
 <%@ page import="org.hibernate.Session" %>  
 <%@ page import="java.sql.Connection" %>  
 <%@ page import="java.sql.ResultSet" %>  
 <%@ page import="java.sql.Statement" %>  
 <%@ page contentType="text/html;charset=UTF-8" language="java" %>  
 <html>  
 <head>  
   <title>Daily Deposits</title>  
   <style type="text/css">  
     table {  
       border-collapse: collapse;  
     }  
     table, th, td {  
       border: 1px solid black;  
     }  
     td, th {  
       padding: 5px;  
     }  
   </style>  
 </head>  
 <body>  
 <jsp:include page="k2_menu.jsp" />  
 <h1>Daily Deposits</h1>  
 <%  
   Session hSession = SessionSingleton.instance();  
   Connection conn = hSession.connection();  
   try {  
     Statement stmt = conn.createStatement();  
     ResultSet rs = stmt.executeQuery("select * from k2_deposits(60)");  
     ResultSetToHtmlTable resultSetToHtmlTable = new com.todacell.util.sql.ResultSetToHtmlTable();  
     resultSetToHtmlTable.writeTable(rs, out,  
         new com.todacell.util.sql.ResultSetToHtmlTable.Column[] {  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.DATE, "Date", ResultSetToHtmlTable.ColumnAlign.LEFT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.CURRENCY, "Deposits", ResultSetToHtmlTable.ColumnAlign.RIGHT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.CURRENCY, "Allocated", ResultSetToHtmlTable.ColumnAlign.RIGHT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.CURRENCY, "Deallocated", ResultSetToHtmlTable.ColumnAlign.RIGHT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.CURRENCY, "Ad Spend", ResultSetToHtmlTable.ColumnAlign.RIGHT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.CURRENCY, "Potential Spend", ResultSetToHtmlTable.ColumnAlign.RIGHT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.INTEGER, "New Users", ResultSetToHtmlTable.ColumnAlign.RIGHT)  
         });  
   } finally {  
     if (hSession != null) {  
       hSession.close();  
     }  
   }  
 %>  
 </body>  
 </html>  
And here is how it looks on the browser:
DOWNLOAD: You can download the ResultSetToHtmlTable here

Tuesday, March 22, 2011

How to Jump to an Anchor using JavaScript

Just like links/urls are a great way of moving between pages, anchors are great way of moving between locations on the same page.
Suppose we would like to move to a specific location on a page above some <div> tag. All we have to do is simply put an <a> tag above that div and give it some name. For example:
<a name="example"></a>
<div>
...
...
...
</div>

How do we jump to this specific location (named: example)? By putting an <a> on the place from which we would like to jump to this location. For example, somewhere else on the page we put:

<a href="#example">Press here to show example</a>

Note, that the name of the anchor for which we would like to jump contains the hash sign (#) as a prefix.

Now, suppose we would like to jump to some location by clicking something other than <a> (anchor) tag. For example by clicking a simple button. How can we jump to that location? Since we are not using anchor tag, we can no longer be directed to that location automatically.

We can use JavaScript in order to accomplish exactly the same behavior. Let’s see how it can be easily done with our button and by setting the “window.location.hash” property :

<input type="button" value="Press here to show example" onclick="window.location.hash = 'example';"/>

Note that on the JavaScript code we no longer need to use the hash (#) prefix.

Tuesday, March 15, 2011

Getting radio button value from radio group using jQuery

Getting radio button value from a group of radio buttons is an easy task using jQuery. All you have to do is to apply the correct selector. If we have a group of radio buttons named: radioGroup all if we have to do is:
$('input[name=radioGroup]:checked').val();
Let's have a look how it looks on a real HTML page containing 3 radio buttons and a check button. By clicking the “Check Value” button we will open an alert popup showing the selected radio value:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> TEST </title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>  
  <input type="radio" id="inpSmall" name="radioGroup" value="small" checked><label for="inpSmall">Small</label><br>
  <input type="radio" id="inpMedium" name="radioGroup" value="medium"><label for="inpMedium">Medium</label><br>
  <input type="radio" id="inpLarge" name="radioGroup" value="large"><label for="inpLarge">Large</label><br><br>
  <input value="Check Value" type="button" onclick="alert('Radio group value: ' + $('input[name=radioGroup]:checked').val());">
</body>
</html>

Sunday, November 8, 2009

Automatically remove HTML remarks with Facelets

If you are working with Facelets, you can easily remove all you HTML remarks on the resulted page, by simply adding this directive in your web.xml:

<context-param>
  <param-name>facelets.SKIP_COMMENTS</param-name>
  <param-value>true</param-value>
</context-param>

Tuesday, August 18, 2009

Sending HTML Email with embedded Images using Apache Commons EMail

Sometimes we would like to send emails that have better looking and are more rich in their content. Today’s most email clients know to show HTML email content. That means that the body of the email is actually HTML rather than plain text. Sending HTML emails is quite simple and can be done using Apache Commons Email. Here is an example class built on Apache Commons Email that sends HTML email:

package com.bashan.blog.mail;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
public class Mailer {
  protected String host;
  protected String username = null;
  protected String password = null;
  protected boolean isTLS = false;
  public Mailer(String host, String username, String password, boolean isTLS) {
    this.host = host;
    this.username = username;
    this.password = password;
    this.isTLS = isTLS;
  }
  public Mailer(String host, String username, String password) {
    this(host, username, password, false);
  }
  public Mailer(String host) {
    this(host, null, null, false);
  }
  public void sendHTMLMail(String fromEmail,
                           String fromName,
                           String[] toEmail,
                           String[] toName,
                           String subject,
                           String html,
                           String alternateText) throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(host);
    email.setFrom(fromEmail, fromName);
    for (int i = 0; i < toEmail.length; i++) {
      email.addTo(toEmail[i], toName[i]);
    }
    if (username != null) {
      email.setAuthentication(username, password);
    }
    email.setTLS(isTLS);
    email.setSubject(subject);
    email.setHtmlMsg(html);
    email.setTextMsg(alternateText);
    email.send();
  }
}

In order to use this code, make sure to put “commons-email.jar” as well as “mail.jar” (Java mail) in your class path. The latest version of “mail.jar” can be easily found by searching “java mail” in Google and downloading from Sun web site.

Note that the method “sendHTMLMail” contains property named: “alternateText”. This property is used for mail clients that does not support receiving HTML mails.

Suppose we would like to make our HTML email look better and add some image to it. We don’t want the image to be sent as a regular attachment. We would like the image to be embedded in our HTML mail message by using the image tag (img).

Luckily, Apache Commons Email supplies a simple way of doing it by using the “embed” method. For example, in order to embed an image that is placed in some URL we can do:

String id = email.embed(new URL("http://server.com/someimage.png"), "Example");

Note that “embed” method takes 2 arguments. First is the URL pointing to the image location and second is the image name. Note also that the “embed” method returns a String id. This id is used as a reference to the image embedded in the mail message. For example, our HTML mail message can look like:

email.setHtmlMsg("<html><body><image src='cid:" + id + "'></body></html>");

Note that the embedded image is referenced by using the prefix: “cid:” in the image “src” property.

As you can see, the embed method returns an id that is being later used in the construction of the HTML. this makes it a bit harder embedding images in HTML mail messages, since we don’t know the id of the embedded image when passing the HTML code as an argument. We can easily solve this problem by defining our own convention of referencing the embedded images that will later will be replaced with the proper id. Our convention will be: Each embed resource which we would like to embed in our HTML code will be named:

${resource number}

For example, suppose we would like to embed a single image. our HTML code will look like:

<html><body><img src='${0}' /></body></html>

Where the: ${0} means, we would like to put our first image in the “src” property.

Support we have 2 images that we want to use 4 times in our HTML. For example:

<html>
  <body>
    <img src='${0}' />
    <img src='${1}' />
    <img src='${0}' />
    <img src='${1}' />
  </body>
</html>

In this example we want to embed in our HTML 2 images and show them one after another twice. Of course that in the code, we will make sure to replace all the occurrences with: ${resource number} with the proper id of the embedded image.

Since an embedded resource is actually defined by 2 parameters: URL and name, we will define an inner static class that will represent a resource. This class is named: Resource. The class is pretty straight forward and need no explanations. An array of this class will be used for passing our method as many resources as we would like to embed in our HTML mail message. Of course that the “resource number” signifies the position of the resource we would like to embed in our Resources array. For example: “${3}” means we would like to embed the 4th resource from our resources array.

We can now have a look at our complete “sendHTMLMail” method that also knows to send multiple embedded resources along with the HTML mail message. Note that the old method for sending HTML mails without resources is still supported:

package com.bashan.blog.mail;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import java.net.MalformedURLException;
import java.net.URL;
public class Mailer {
  protected String host;
  protected String username = null;
  protected String password = null;
  protected boolean isTLS = false;
  public Mailer(String host, String username, String password, boolean isTLS) {
    this.host = host;
    this.username = username;
    this.password = password;
    this.isTLS = isTLS;
  }
  public Mailer(String host, String username, String password) {
    this(host, username, password, false);
  }
  public Mailer(String host) {
    this(host, null, null, false);
  }
  public void sendHTMLMail(String fromEmail,
                           String fromName,
                           String[] toEmail,
                           String[] toName,
                           String subject,
                           String html,
                           String alternateText,
                           Resource[] resources) throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(host);
    email.setFrom(fromEmail, fromName);
    for (int i = 0; i < toEmail.length; i++) {
      email.addTo(toEmail[i], toName[i]);
    }
    if (username != null) {
      email.setAuthentication(username, password);
    }
    if (resources != null) {
      int i = 0;
      for (Resource resource : resources) {
        String id = email.embed(resource.getUrl(), resource.getName());
        html = html.replaceAll("\\$\\{" + i++ + "\\}", "cid:" + id);
      }
    }
    email.setTLS(isTLS);
    email.setSubject(subject);
    email.setHtmlMsg(html);
    email.setTextMsg(alternateText);
    email.send();
  }
  public void sendHTMLMail(String fromEmail,
                           String fromName,
                           String[] toEmail,
                           String[] toName,
                           String subject,
                           String html,
                           String alternateText) throws EmailException {
    sendHTMLMail(fromEmail, fromName, toEmail, toName, subject, html, alternateText, null);
  }
  public static class Resource {
    private URL url;
    private String name;
    public Resource(URL url, String name) {
      this.url = url;
      this.name = name;
    }
    public Resource(String url, String name) throws MalformedURLException {
      this(new URL(url), name);
    }
    public URL getUrl() {
      return url;
    }
    public void setUrl(URL url) {
      this.url = url;
    }
    public String getName() {
      return name;
    }
    public void setName(String name) {
      this.name = name;
    }
  }
  public static void main(String[] args) throws Exception {
    new Mailer("smtp.gmail.com", "youruser@gmail.com", "yourpassword", true).sendHTMLMail(
        "admin@test.com", "Tester", new String[]{"guy.bashan@gmail.com"}, new String[]{"Guy Bashan"}, "Testing HTML Email",
        "<html><body><table><tr><td>Image 1</td><td>Image 2</td></tr><tr><td>" +
            "<img src='${0}'/></td><td><img src='${1}'/></td></tr></table></body></html>", "alternate HTML",
        new Resource[]{new Resource("http://www.google.com/intl/en_ALL/images/logo.gif", "Google Logo 1"),
            new Resource("http://www.google.com/intl/en_ALL/images/logo.gif", "Google Logo 2")});
  }
}

In the bottom of the Mailer class you can find a small test program that sends HTML mail message with 2 embed images of Google logo.

Thursday, May 21, 2009

Directly download a file by pressing a link using Java Servlet

There are times in which we would like to directly download a resource by pressing on a link on a page. The meaning of directly is:
  • The browser dialog will be open asking where to save the resource.
  • After saving the file the browser will stay on the same page without doing any refresh or opening a child window.

Usually this is useful if we would like to allow the user to download some real time dynamically generated file that is being created on the server side.
For the example we will use the ZipDir class from this post. We will see how we can allow the user download a dynamically created zip file by pressing on a link.

In general, in order to achieve the above behavior we have to instruct the response with 2 instructions:

  • Set the response content type to: “application/zip”. This is in the case of sending back to the client a Zip file. For any other file type we should set the correct content type. For example, if we would like to send back to the client a PDF file the following content type should be used: “application/pdf”.
  • Set response header: “Content-disposition” with the following value: “attachment; filename=<filename>”, where filename is the name of the file we want the user to see in the “save” dialog.

Here is an example of a Servlet that generates a Zip file on the fly and sends it back to the browser:

package com.bashan.blog.zip;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ZipServlet extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/zip");
    response.setHeader("Content-disposition", "attachment; filename=demo.zip");
    ServletOutputStream outputStream = response.getOutputStream();
    new ZipDir("/somedir", outputStream).zip();
  }
}

Note that our ZipDir class is smart enough to set the generated Zip file directly to the output stream of the response. That is a neat solution saving us from needing to generate temporary Zip files on the server that later will have to be deleted.

Nothing special on the web.xml file, just define a Servlet, with “zip” url pattern:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           version="2.5">
    <servlet>
      <servlet-name>Zip Servlet</servlet-name>
      <servlet-class>com.bashan.blog.zip.ZipServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
      <servlet-name>Zip Servlet</servlet-name>
      <url-pattern>/zip</url-pattern>
    </servlet-mapping>
      
</web-app>

And finally, a sample HTML page with a download link to the Zip resource:

<html>
 <head>
  <title> Zip Download Sample Page </title>
 </head>
 <body>
 <h3>Zip download sample page</h3>
 Press this link: <a href="zip">Download Zip resource</a>
 </body>
</html>
Note that we call “zip” Servlet directly as a relative path to the server context.

Sunday, April 19, 2009

Inputting only numbers using Java Script and HTML

The basic input text field of HTML is very limited when it comes numeric data. There are times in which a better user experience is needed.
In order to generate a better user experience, 2 main features can be easily added to the input text field by using JavaScript:
  • Allow user to input only numeric data. That means that any character other than numbers dots or commas is not allowed. This feature prevents from the user to entering undesired data to the field.
  • Show data in a formatted manner when field is not edited. That means that when field lost focus, its contents are shown with commas or dots. That makes the numeric data on the text field to be more readable.
Note, that we also would like the text to be formatted according to a specific Locale. That means that we want to use decimal separator and grouping separator to be according to our demands. There are countries and cultures in which the decimal separator is comma and some other countries in which decimal separator is dot. The same applies to grouping separator.
In order to achieve our 2 goals we will build 3 java script functions. Each function will be assigned to a specific JavaScript event.
  • onkeypress: This event is activated whenever a key is being pressed when the cursor is in the text field. A function that returns "false" on this event cancels the event and thus prevent from the pressed character to be updated on the text field. We will assign to this even a function named: numbersOnly. This function receives 4 parameters:
    • field: The text field that called the function.
    • e: The onkeypress event.
    • isDec: Indicate that we would like the input to be decimal and not only integer.
    • decimalSeperator: The character used as a decimal separator (probably “.” or “,”).
    In return this function will return true whenever the pressed character is allowed to be inputted by the user or false if character is not allowed to be inputted.
  • onfocus: This event is activated when the text field receives focus. That means, when we are entering to the text field. This event will be assigned with a function named: plainNumber. This function takes the numeric data in the text field and converts it to a plain number, meaning, any numeric formatted data containing dots or command will be converted to a plain number ready to be edited. This function has 2 parameters:
    • field: The text field field that called the function.
    • decimalSeperator: The character used as a decimal separator (probably “.” or “,”).
  • onblur: This event is activated when the field loses focus. That means when we are entering the field by moving to another element on the page. This event will be assinged with a function named: formattedNumber. This function converts the plain numeric data on the text field to a formatted data containing grouping separators. This function has 3 parameters:
    • field: The text field field that called the function.
    • decimalSeperator: The character used as a decimal separator (probably “.” or “,”).
    • groupingSeperator: The character used as a grouping separator (probably “.” or “,”).

I made an example showing a text field utilizing the 3 events to create the described behavior. The example contains a simple HTML page containing the JavaScript methods and a simple text field. The JavaScript code used in this example is not state of the art, but working fine on both FireFox and Explorer. This code can be further refined by encapsulating all the behavior to a single static JavaScript class.

Here is the example code showing input numbers only of an Integer number:

<html>
 <head>
  <title> JavaScript Input Example </title>
 </head>
 <body>
<script>
function numbersOnly(field, e, isDec, decimalSeperator)
{
  var key;
  var keychar;
if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
  keychar = String.fromCharCode(key);
// control keys
  if ((key == null) || (key == 0) || (key == 8) ||
      (key == 9) || (key == 13) || (key == 27) || (key == 39) /*|| (key == 37)*/)
  {
    return true;
  }
  else if ((("0123456789").indexOf(keychar) > -1) ||
    (isDec && (keychar == decimalSeperator) && (field.value.indexOf(decimalSeperator) < 0)))
  {
    return true;
  }
 return false;
}
function formattedNumber(field, decimalSeperator, groupingSeperator)
{
    field.value = addGroupingSeperator(field.value, decimalSeperator, groupingSeperator);
}
function plainNumber(field, decimalSeperator)
{
    field.value = field.value.replace(
        new RegExp("[^0123456789" + decimalSeperator + "" + "]", 'g'), "");
}
function addGroupingSeperator(nStr, decimalSeperator, groupingSeperator)
{
    nStr += '';    
    x = nStr.split(decimalSeperator);
    x1 = x[0];
    x2 = x.length > 1 ? decimalSeperator + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + groupingSeperator + '$2');
    }
    return x1 + x2;
}
</script>
    <input id="inputInteger" name="inputInteger" maxLength="7"
       onfocus="plainNumber(this, '.');"
       onblur="formattedNumber(this, '.', ',')"
       onkeypress="return numbersOnly(this, event, false, '.')">
 </body>
</html>
Note that the data of the decimal and grouping separator can be taken from your programming language and assigned dynamically according to the specific user Locale information.