Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, December 17, 2010

Form Validation using checkValidity and Validity in HTML 5 using JavaScript- Sample Code

The next major version of the HTML standards (HTML 5) seem to have numerous improvements over the current standards. Most of the functionalities, for which the developers has to write extensive custom code, will get reduced to a certain extend by the launch of new standards.

The below sample shows how to perform a FORM validation for an HTML 5 input element using the newly introduced "Validity" property associated to an input element. This will also demonstrate the usage of checkValidity() function which can be used to identify whether the the form elements are all validated to proceed with the server communication.

Skill level: For Beginners

Sample Code:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8">
<title>HTML5 Sample Validation Page</title>
<style type="text/css">
body
{
    font-family:Arial;
    font-size:12px;
}
.valid
{
    color:#000000;
}
.invalid
{
    color:#FF0000;
}
</style>
</head>
<body>
<form id="form1" method="post">

<label>Age: <input type="number" required="true" value="50" min="18" max="60" step="1" oninput="validate(this)"> (between 18 and 60)</label><br /><br />
<div id="validateMsg"></div><br />
<div id="validity"></div>
<script>
    function validate(input) {
        var out = document.getElementById('validateMsg');
        if (input.validity) {
            if (input.validity.valid === true) {
                out.innerHTML = "<span class='valid'>" + input.value +
                            " is a valid age.</span>";
            } else {
                out.innerHTML = "<span class='invalid'>" + input.value +
                            " is not valid age.</span>";
            }
        }
        document.getElementById('validity').innerHTML = "checkValidity() output: <span class='invalid'>" + input.checkValidity() + "</span>";
    }
</script> 
</form>
</body>
</html>

Concept:
The input element is a number element (that accepts "Age") in this example, with maximum and minimum values set in the design mode. [If more information is needed on the Input elements, refer here.] During the user input event, a JavaScript function validate() is called. This function validates the input value using the input.validity.valid property and provides appropriate message, after checking for the support of this functionality.

checkValidity() function is called to check and understand the value that it returns for the successful and unsuccessful validation scenarios.

Here are the output screens:

Valid Input:

Invalid Input:

As you can see, the checkValidity() always seems to return false. It returns true for values less than 10. It is being suspected that the inadequate browser support is one reason behind this weird behavior OR i'm missing something. However, as per the documentation here, this function will help us to check and trigger functions based on the invalid/valid state of one/multiple elements, thereby assisting us in form validations.

In the above code, the script tag is provided inside the body tag, for the sake of easy understanding. Keep it inside the HEAD tag, as it is usually done.

Saturday, February 13, 2010

Create simple and reusable objects for AJAX in JavaScript – ajaxRequest

Well, there are similar ones out there. jQuery, YUI and AjaxObject are just to name a few, which has their own implementations along with other in-built functionalities. Then there is mine, which is done in a much simpler way with the cost of flexibility. If you’re just looking for a simple reusable JavaScript class for making AJAX calls (and AJAX calls only), you're at the right place.

For Beginners:
For the sake of the simplicity of this article, i will not be going in much detail about the basics of HTTP calls, the different modes (POST, GET) of communications and their related topics. Let’s just say that, an HTTP call or an AJAX call can be made to a URL (Ex: http://www.mywebsite.com) using either GET (where URL has all the information like http://www.mywebsite.com?name=john&age=25) or POST (where the form data is submitted as key-value pair like key1=value1&key2=value2 with appropriate header information on the request). Oops! did i just said everything about HTTP calls in one sentence? No, there is more.

The ajaxRequest Snippet
Here is the ajaxRequest’s code. The code is pretty straightforward and is designed in such a way that it works with minimum arguments. There are comments embedded in the code (download from below) and sample usage code provided below to make it’s use seamless.

function ajaxRequest(url, method, postData) {
//validation start
if (url == undefined) return false;
this.method = method == undefined ? "GET" : method.toUpperCase();
if (this.method != "GET" && this.method != "POST") return false;
if (url == undefined || url == "") return false;
//validation end
this.url = url + ((url.indexOf('?') > 0) ? "&ajts" : "?ajts") + new Date().getTime();
var mainCls = this;
this.inProgress = false;
this.xmlHttpObj = null;
this.postData = postData;
this.toString = function() { return "Ajax by Sanal"; }
this.abort = function() {
if (mainCls.inProgress) {
mainCls.xmlHttpObj.abort();
mainCls.inProgress = false;
mainCls.xmlHttpObj = null;
}
}
this.execute = function(statusChangeFunction) {
try {
// Firefox, Opera 8.0+, Safari
mainCls.xmlHttpObj = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
mainCls.xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
mainCls.xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {

return false; //No support for AJAX
}
}
}

mainCls.xmlHttpObj.onreadystatechange = function() {
if (statusChangeFunction) {
statusChangeFunction(mainCls.xmlHttpObj.readyState, typeof (mainCls.xmlHttpObj.responseText) == "unknown" ? null : mainCls.xmlHttpObj.responseText, typeof (mainCls.xmlHttpObj.responseXML) == "unknown" ? null : mainCls.xmlHttpObj.responseXML, mainCls.xmlHttpObj.readyState==4 ? mainCls.xmlHttpObj.status : null);
}
if (mainCls.xmlHttpObj.readyState == 4) {
mainCls.inProgress = false;
mainCls.xmlHttpObj = null;
}
}

mainCls.xmlHttpObj.open(mainCls.method, mainCls.url, true);
if (mainCls.method == "POST") {
mainCls.xmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mainCls.xmlHttpObj.setRequestHeader("Content-Length", mainCls.postData.length);
}
mainCls.inProgress = true;
mainCls.xmlHttpObj.send(mainCls.method == "POST" ? mainCls.postData : null);
return true;
}
}

Code Download
The above code with embedded comments, along with the minified version, can be downloaded from here. [In case, if you don't know, minified version will not have the comments and spaces, to keep the file size to a minimum possible, making the server-browser communication faster.]

Sample usage:
Provide a reference

First, let the browser know that it needs to load the script.

If you're using the minified version, change the file name appropriately.

Create an Object
Then, in another scripting place, create an object for ajaxRequest as shown below. In the example below, the testAjax function will be the function that triggers the AJAX call to the server url “ajaxprocessor.aspx” which in turn processes the aynschronous requests. Since there are no other arguments passed, the call is defaulted to a GET call and the URL is expected to have input parameters for server processing.

function testAjax() {
var myAjaxRequest = new ajaxRequest("ajaxprocessor.aspx?name=john");
myAjaxRequest.execute(processMyRequest);
myAjaxRequest = null;
}

One minor point to note here. Among the query strings that are being passed to the URL, it is not recommended to use the key "ajts" (AJAX timestamp) since that is being used by the ajaxRequest to make every AJAX call unique to the browser. This is applicable to both GET and POST requests.

Track your AJAX call
The “processMyRequest” function in the above code is the callback method, that gets executed when for every state change of your AJAX call. A simple implementation of the “processMyRequest” can be something like this. I’m assuming that you have a DIV with the id “myDIV” placed in your web page. [Beginners, you might want to know more about readyState and status for asynchronous calls]

function processMyRequest(readyState, responseText) {            
if (readyState == 1)//loaded
document.getElementById("myDIV").innerHTML = "Loading...";
else if (readyState == 4)//complete
document.getElementById("myDIV").innerHTML = responseText;
}

The callback function can be created with any number of arguments depending on the need. The arguments are in the order as specified in the main ajaxRequest code comments.

The sample approach can be used to make a POST call by changing the object creation as

var myAjaxRequest = new ajaxRequest("ajaxprocessor.aspx","POST","key1=value1&key2=value2”);

Refer the downloaded ajaxRequest code for more technical details on each of these methods and variables.

Browser Compatibility
This code has been tested with IE, Firefox and Chrome and is expected to be working in most of the browsers. If problems are found, share them so that everyone will know.

Enhancements
Well, as mentioned at the beginning of this article, this might not be flexible enough. if you dig deep enough, you might find functionalities that could’ve included to make it better. Feel free to change the code for your usage and let me know what was missing.

Thursday, February 4, 2010

Retrieve an element's width or height using JavaScript

Even though, not 100% browser independent, the following JavaScript code will get you an element's current/rendered width or height. The code is pretty simple and self-explanatory.

Code to retrieve element's width:
function getWidth(element){

    if (typeof element.clip !== "undefined") //netscape
    {
        return element.clip.width;
    }
    else {
        if (element.style.pixelWidth)//opera 
        {
            return element.style.pixelWidth;
        }
        else //IE and firefox
        {
            return element.offsetWidth;
        }
    }
}
Code to retrieve element's height:
function getHeight(element){

    if (typeof element.clip !== "undefined")    //netscape
    {
        return element.clip.height;
    }
    else {
        if (element.style.pixelHeight) //opera
        {
            return element.style.pixelHeight;
        }
        else //IE and firefox
        {
            return element.offsetHeight;
        }
    }
}
Sample Usage:
function usage(){
 alert(getWidth(document.getElementById("yourElementId")));
}
This code works for most of the input (dropdown/select-one/Select-multiple, textbox, textarea) elements in an HTML form. Feel free to share any better solutions.

Friday, December 18, 2009

Get and Set values for all form elements using JavaScript


Here, we will cover the basic logic to retrieve and set values for various HTML form elements using a sample JavaScript code.

This discussion assumes that you are familiar with the methods like document.getElementById, document.getElementsByName etc.. to find and load the element for further processing. For a quick note, if it is assumed that you have a textbox with id, ‘myText’, then that text can be accessed by document.getElementsById(‘myText’).

The logic is pretty simple and is based on the concept that each element has it’s own individual property to be set. Below is the table that shows just that.

Element Type Property to be used Comments
checkbox checked  
hidden value  
radio checked  
text value  
textarea value  
select-one selected
OR
selectedIndex
This is a dropdown. It can be either set by setting the ‘selected’ property of the options collection OR setting the selectedIndex property of the dropdown itself.
select-multiple selected
OR
selectedIndex
This is multi-select dropdown which is created using multiple="multiple" for a select tag. Works similar to select-one.

To get the value of a particular element, use it’s appropriate property based on the type of the element being processed. The below code shows how that can be done in a simple manner. Note that the select-multiple returns an array of selected values. This code is presented in simple if..else syntax for simplicity. Provide error catching mechanism as necessary.

function getValue(element)//returns the value
{
if (element==null) return null;
var returnValue;
if (element.type=="select-one")
{
//dropdown (select-one)
returnValue = element.options[element.selectedIndex].value;
}
else if (element.type=="select-multiple")
{
//multi-select drop down
var returnArray = new Array();
for(var i = 0; i < element.options.length; i++)
{
if(element.options[i].selected == true)
{
returnArray.push(element.options[i].value);
}
}
return returnArray;
}
else if (element.type=="checkbox")
{
//checkbox element
returnValue = Boolean(element.checked);
}
else if (element.type=="radio")
{
//radio element
returnValue = Boolean(element.checked);
}
else
{
//text, textarea, hidden
returnValue = element.value;
}
return returnValue;
}

To set the value, it’s just the reverse process, which is shown below.

function setValue(element, value)//return whether the set was successful.
{
if (element==null) return false;
if (value==null) return false;
var returnValue;
if (element.type=="select-one")
{
//dropdown (select-one)
for(var i = 0; i < element.options.length; i++)
{
if(element.options[i].value == value)
{
element.selectedIndex = i;
returnValue = true;
break;
}
}
}
else if (element.type=="select-multiple")
{
//multi-select drop down, expects the value to be an array of selected values
for(var j = 0; j < value.length; j++)
{
for(var i = 0; i < element.options.length; i++)
{
if(element.options[i].value == value[j])
{
element.options[i].selected = true;
break;
}
}
}
returnValue = true;
}
else if (element.type=="checkbox")
{
//checkbox element
element.checked = Boolean(value);
returnValue = true;
}
else if (element.type=="radio")
{
//radio element
element.checked = Boolean(value);
returnValue = true;
}
else
{
//text, textarea, hidden
element.value = value;
returnValue = true;
}
return returnValue;
}

Additional thoughts:
If, the controls are rendered from an ASP.net application, there may be times where the value from a Label control is to be set or retrieved. Since a Label is rendered as a SPAN element, this can be done by enhancing the code for checking the nodeName OR tagName (or any appropriate property) and using innerHTML to set or get the value of the SPAN element.


Thursday, October 29, 2009

Two dimensional Array (Table Array) Multiple column sorting using JavaScript

Here is a JavaScript implementation for multi-column ascending sort on a table array.

Below is the code for this.
var tempArray = new Array();
//main function
function do2DArraySort(arrayToBeSorted, sortColumnArray)
{
if (arrayToBeSorted == "undefined" || arrayToBeSorted == "null") return arrayToBeSorted;
if (arrayToBeSorted.length == 0) return arrayToBeSorted;
if (sortColumnArray.length == 0) return arrayToBeSorted;
tempArray = arrayToBeSorted; 
var totalLength = sortColumnArray.length; 
for(var m = 0; m < totalLength; m++)
{
if (m == 0)
{   
doBubbleSort(tempArray, tempArray.length, sortColumnArray[m]);         
}
else
{     
doMultipleSort(tempArray, sortColumnArray[m], sortColumnArray[m-1]);
}
} 
return tempArray;
}

//basic bubble sort implementation
function doBubbleSort(arrayName, length, element) 
{
for (var i = 0; i < (length-1); i++)
{
for (var j = i+1; j < length; j++)            
{
if (arrayName[j][element] < arrayName[i][element]) 
{
var dummy = arrayName[i];
arrayName[i] = arrayName[j];
arrayName[j] = dummy;
}
}
}  
}

//appends an array content to the original array
function addToArray(originalArray, addArray)
{
if (addArray.length != 0)
{
var curLength = 0;
curLength = originalArray.length;
var maxLength = 0;
maxLength = curLength + addArray.length;  
var itrerateArray = 0;
for (var r = curLength; r < maxLength; r++)
{   
originalArray[r] = addArray[itrerateArray];
itrerateArray++;
}
}
}

//check if a value exists in a single dimensional array
function checkIfExists(arrayToSearch, valueToSearch)
{
if (arrayToSearch == "undefined" || arrayToSearch == "null") return false;
if (arrayToSearch.length == 0) return false;
for (var k = 0; k < arrayToSearch.length; k++)
{
if (arrayToSearch[k] == valueToSearch)
return true;
}
return false;
}

//sorts an 2D array based on the distinct values of the previous column
function doMultipleSort(sortedArray, currentCol, prevCol)
{
var resultArray = new Array(); 
var newdistinctValuesArray = new Array();
//finding distinct previous column values 
for (var n = 0; n < sortedArray.length; n++)
{ 
if (checkIfExists(newdistinctValuesArray, sortedArray[n][prevCol]) == false)
newdistinctValuesArray.push(sortedArray[n][prevCol]);
}  
var recCursor = 0;
var newTempArray = new Array(); var toStoreArray = 0; 
//for each of the distinct values
for (var pp = 0; pp < newdistinctValuesArray.length; pp++)
{
toStoreArray = 0;
newTempArray = new Array();  
//find the rows with the same previous column value
for (var qq = recCursor; qq < sortedArray.length; qq++)
{
if (sortedArray[qq][prevCol] != newdistinctValuesArray[pp]) break;
newTempArray[toStoreArray] = sortedArray[qq];
toStoreArray++; recCursor++;
}
//sort the row based on the current column   
doBubbleSort(newTempArray, newTempArray.length, currentCol);
//append it to the result array
addToArray(resultArray, newTempArray);
}
tempArray = resultArray;
}
The above code can be stored as TableArrayMultipleSort.js for our example usage shown below:
<html>
<head>
<title>Invoking Multiple Array Sort</title>
<script language="javascript" src="TableArrayMultipleSort.js" type="text/javascript"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
function createSampleArray()
{ 
var myArr = new Array( 
new Array("Ashley","13","Male","Texas"),
new Array("Smith", "32", "Male","Colorado"),
new Array("Jane", "21", "Female","South Carolina"),
new Array("Anna", "12", "Female","Maryland"),
new Array("Ashley","13","Male","Delaware"),
new Array("Ashley","46","Male","Newyork")
); 
return myArr;
}
function showDataByRow(arrayToBeShown)
{
for(var a=0;a<arrayToBeShown.length;a++)
{
document.write(arrayToBeShown[a]+"<br>");
}
}
document.write("<b>Original Array: (Input)</b>" + "<br><br>");
showDataByRow(createSampleArray());
document.write("<br><br><br>");
var sortColumnArray = new Array('0','1','3'); 

document.write("<b>Sorted Array: (Output)</b><br>Order: First column, then by second column and then by Last Column" + "<br><br>");
showDataByRow(do2DArraySort(createSampleArray(),sortColumnArray));
</script>
</body>
</html>
When the above code is executed, this will show the input table array and output table array as shown below. Original Array: (Input)
Ashley,13,Male,Texas
Smith,32,Male,Colorado
Jane,21,Female,South Carolina
Anna,12,Female,Maryland
Ashley,13,Male,Delaware
Ashley,46,Male,Newyork
Sorted Array: (Output) Order: First column, then by second column and then by Last Column
Anna,12,Female,Maryland
Ashley,13,Male,Delaware
Ashley,13,Male,Texas
Ashley,46,Male,Newyork
Jane,21,Female,South Carolina
Smith,32,Male,Colorado
Enhancements: 1. The code can be enhanced to accomodate sort order for each of the sort columns by having a seperate array to specify that.
2. It can be relooked for performance improvements and enhanced variable handling.
3. There are few issues related to null/empty-value, if it exists in any of the columns being sorted.


Note: The objective of this article is to assist in learning the Javascript array concepts and it's usage. This code is not intended to be used for production purposes as it is not written with that aspect in mind. So, if you want to use it, use it at your own risk.