Sunday, February 28, 2010

How to create arrays in JavaScript

How to Create Arrays in JavaScript?

Following example shows you how to create Arrays in JavaScript.



An array is a special variable type, which can hold more than one value in it at a time. Arrays are declared using the Array() constructor. An array can hold data types such as Boolean values, String values, floating point numbers or Objects in it. Values in an array called 'elements'. Every array element has an index. Normally first array element has the zero index. We can get the total array elements using length property of the array. Arrays can be single dimension or multi-dimensional. If you have long list of values such as a country list; how do you declare that values in your program? You can define one or two variable to store 1 or two countries. But can you declare variable of all items in that list? It is not a possible task. The easiest way is the define an Array to store that data.

Demo- Create arrays in JavaScript.




How to Declare Arrays in JavaScript?

Declare an empty array in JavaScript.

var emptyAarray=new Array();

Declares an array with 7 elements.

var days=new Array("Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday","Saturday");

Declare an empty array with which can hold five elements.

var letters=new Array(5); five elements in it. letters[0]="A"; letters[1]="B"; Likewise you can assign values to Array elements.

Accessing array elements.

You can access array elements using for loop. Also you can assign values to array elements looping through for loop.

<scrip type="text/javascript"t> var marks=new Array(58,45,79,86,93,60,55); for(var i=0;i<marks.length;i++){ document.write(marks[i]+"-"); } </script>

out put 58-45-79-86-93-60-55

How to store objects in an array?

You can store Objects in a array as same as storing other values.

<script type="text/javascript" language="javascript"> var box1=Object(); box1.width=34; box1.height=45;

var box2=Object(); box2.width=200; box2.height=100;

var boxes=new Array(box,box2); alert(boxes.length);//output = 2

alert(boxes[0].width);// out put = 34 </script>

How to create multi dimensional arrays in JavaScript?

<script type="text/javascript" language="javascript"> var multiplicationTable=[[2,4,6], [3,6,9], [4,8,12], [5,10,15], [6,12,18]]; alert(multiplicationTable[3][2]);//out put=15 alert(multiplicationTable[0][0]);//out put=2 </script>

Array Methods

concat() method Concatenates elements from one array to another array.

<script type="text/javascript" language="javascript"> var array1=new Array("Red","Green","Blue"); var array2=new Array("Pink","Black","Orange","Green"); var array3=array1.concat(array2); document.write(array3); </script>

Out put: Red,Green,Blue,Pink,Black,Orange,Green
join() converts the array to a string and allows you to specify how the elements are separated in the resulting string.

<script type="text/javascript" language="javascript"> var array1=new Array("Red","Green","Blue","Pink","Black"); document.write(array1.join("-"));//Out put: Red-Green-Blue-Pink-Black document.write(array1.join("/")); //Out put: Red/Green/Blue/Pink/Black </script>

pop() method Removes and returns the last element of an array.

<script type="text/javascript" language="javascript">

var array1=new Array("Red","Green","Blue","Pink","Black"); document.writeln(array1.pop());//Out put: Black document.writeln("<br/>"); document.writeln(array1); //Out put Red,Green,Blue,Pink

</script>

push() method adds elements to the end of an array You can add any number of elements to the end of the array using push() method.

<script type="text/javascript" language="javascript">

var array1=new Array("Red","Green","Blue","Pink"); document.writeln(array1);//Out put: Red,Green,Blue,Pink document.writeln("<br/>"); array1.push("Black"); document.writeln(array1); //Out put: Red,Green,Blue,Pink,Black

</script>

reverse() method Reverses the order of the elements in an array.

<script type="text/javascript" language="javascript">

var array1=new Array("1","2","3","4","5"); document.writeln(array1);//Out put: 1,2,3,4,5 document.writeln("<br/>"); array1.reverse(); document.writeln(array1); //Out put: 5,4,3,2,1

</script>

shift() Removes and returns the first element of an array.

<script type="text/javascript" language="javascript">

var array1=new Array("Red","Blue","Green","Orange","White"); document.writeln(array1);//Out put: Red,Blue,Green,Orange,White document.writeln("<br/>"); document.writeln(array1.shift());// Out put: Red document.writeln("<br/>"); document.writeln(array1); //Out put: Blue,Green,Orange,White

</script>

slice() method copies elements of one array into a new array. The slice() method takes two arguments. the first number is the starting position of elements that will be copied, and the second argument is the last position in the array.

<script type="text/javascript" language="javascript">

var array1=new Array("Red","Blue","Green","Orange","White","Black"); document.writeln(array1);//Out put: Red,Blue,Green,Orange,White,Black document.writeln("<br/>"); var array2=array1.slice(1,3); document.writeln("<br/>"); document.writeln(array2);//Out put: Blue,Green var array3=array1.slice(2,5); document.writeln("<br/>"); document.writeln(array3);//Out put: Green,Orange,White

</script>

sort() method sorts an array alphabetically.

<script type="text/javascript" language="javascript">

var array1=new Array("Red","Blue","Green","Orange","White","Black"); document.writeln(array1);//Out put: Red,Blue,Green,Orange,White,Black document.writeln("<br/>"); var array2=array1.sort(); document.writeln(array2);//Black,Blue,Green,Orange,Red,White </script>

toString() method returns a string representation of the array.

<script type="text/javascript" language="javascript">

var array1=new Array("Red","Blue","Green","Orange","White","Black","233","345"); document.writeln(array1);//Out put: Red,Blue,Green,Orange,White,Black,233,345 document.writeln("<br/>"); var str1=array1.toString(); document.writeln(str1);//Out put: Red,Blue,Green,Orange,White,Black,233,345 alert(typeof(str1));//alerts 'string'

</script>

unshift() method dds elements to the beginning of an array.

<script type="text/javascript" language="javascript">

var array1=new Array("Red","Blue","Green","Orange"); document.writeln(array1);//Out put: Red,Blue,Green,Orange document.writeln("<br/>"); array1.unshift("White","Black"); document.writeln(array1);//Out put: White,Black,Red,Blue,Green,Orange

</script>

splice() method removes a specified number of elements from specified starting position in an array and allows you to replace that items with new elements. splice() method has two constructors. splice(int starting_point,int items_to_remove) splice(int starting_point,int items_to_remove,replacement_elements)

<script type="text/javascript" language="javascript">

var array1=new Array("Red","Blue","Green","Orange","Black","White"); document.writeln(array1);//Out put: Red,Blue,Green,Orange document.writeln("<br/>"); array1.splice(2,2); document.writeln(array1);//Out put: White,Black,Red,Blue,Green,Orange document.writeln("<br/>");

var array2=new Array("One","Two","Three","Four","Seven","Eight","Nine"); document.writeln(array2);//Out put: One,Two,Three,Four,Seven,Eight,Nine array2.splice(4,2,"Five","Seven"); document.writeln("<br/>"); document.writeln(array2);//Out put: One,Two,Three,Four,Five,Seven,Nine </script>

Bookmark and Share
Try It!
» How to get screen resolution in JavaScript
» How to limit characters in textarea using JavaScript
» How to validate decimal number in JavaScript
» How to validate an email address in JavaScript
» How to validate date using JavaScript
» JavaScript String functions
» How to validate multiple select list box in JavaScript
» How to generate random numbers in JavaScript
» How to validate multiple check box in JavaScript
» How to validate user login in JavaScript
» How to validate drop down list in JavaScript
» How to validate radio button group in JavaScript
» How to create JavaScript alerts
» How to create popup windows in JavaScript
» How to count words in a text area using JavaScript
©-Copyright By Duminda Chamara JavaScript Validation

Sunday, February 21, 2010

How to create javascript alerts


How to Create a JavaScript Alerts?




Following example shows you how to create a JavaScript Alerts.





JavaScript alert is a kind of message box that use to display some information to the user to gain his attention or prompt a input from the user. Suppose that you want to display an error message to the user. Using javascript alert you can do it easily. When you validate user inputs before submit to the server, you can use javascript alert to ask user to enter valid data. Also you can use a confirm dialog box to ask user to make sure that he entered correct data.


Demo- Create JavaScript Alerts.

JavaScript Alert Boxes
  JavaScript alert box show a message to the user.

You can display the message with multiple lines using '\n'
» How to create Simple JavaScript Alert Box
» How to break lines in a javascript alert message
» Display custom message in javascript alert
  Enter your Message
» Display screen size using an alert
» Display the URL of current web page
 
JavaScript Prompt Messages
  JavaScript prompt dialog box provide a text box to the user to enter

text input. Also you can define a default value. It returns user's input if

the user has entered a value. Otherwise it returns the default value.

But it returns 'null' if there is no any value present in the text box.
» Prompt user name
» Adding two numbers using prompt messages
 
JavaScript Confirm Messages
  JavaScript confirm dialog box returns true or false according to
user response. If user clicks on 'Yes' button it returns 'true'
and if user
clicks on 'Cancel' button or close the message window it returns 'false'
» Simple confirm message
» Use confirm dialog to go to another web page



Try It!

Bookmark and Share





1. Example code for create a alert box in javascript.

JavaScript Code

<script type="text/javascript" language="javascript">

<!--

function simpleAlert(){

window.alert("This is a simple javascript alert");

return false;

}

-->

</script>

HTML Code


<html>
<head><title>How to create a simple alert </title>
</head><body>
<table border="0"><tr>
<td>&nbsp;<input name="btnmessage" type="submit" id="btnmessage" onclick="javascript:simpleAlert();" value="Click Here " /></td>
<td>&nbsp;</td></tr>
</table>
</body>
</html>




2. Example code for create a multi line alert in JavaScript.

JavaScript Code

<script type="text/javascript" language="javascript">

<!--

function lineBreakAlert(){

window.alert("You can display multiple lines in your message\n1.This is the second line\n2.This is third line\nUse \'\\n\' to break lines in your message");

return false;

}

-->

</script>

HTML Code


<html>

<head><title>How to create a multiple line alert </title>

</head><body>

<table border="0"><tr>

<td>&nbsp;<input name="btnmessage" type="submit" id="btnmessage" onclick="javascript:lineBreakAlert();" value="Click Here " /></td>

<td>&nbsp;</td></tr>

</table>

</body>

</html>




3. Example code for create a prompt dialog box in JavaScript.

JavaScript Code

<script type="text/javascript" language="javascript">

<!--

function promptName(){

var name=window.prompt("Please enter your Name","");

if(name==null){

alert("Please enter your name");

return false;

}else{

if(name!=""){

alert("Your Name is "+name);

return false;

}else{

alert("Please enter your name");

return false;

}

}

}

-->

</script>

HTML Code


<html>

<head><title>How to create a multiple line alert </title>

</head><body>

<table border="0"><tr>

<td>&nbsp;<input name="btnmessage" type="submit" id="btnmessage" onclick="javascript:promptName();" value="Click Here " /></td>

<td>&nbsp;</td></tr>

</table>

</body>

</html>




4. Example code for create a confirm dialog box in JavaScript.

JavaScript Code

<script type="text/javascript" language="javascript">

<!--

function simpleConfirm(){

var response=confirm("Click \'Ok\' or \'Cancel\'");

alert("You clicked "+(response==true?"Ok":"Cancel")+" button");



}

-->

</script>

HTML Code


<html>

<head><title>How to create a confirm dialog box </title>

</head><body>

<table border="0"><tr>

<td>&nbsp;<input name="btnmessage" type="submit" id="btnmessage" onclick="javascript:simpleConfirm();" value="Click Here " /></td>

<td>&nbsp;</td></tr>

</table>

</body>

</html>





 »   How to get screen resolution in JavaScript
 »   How to limit characters in textarea using JavaScript
 »   How to validate decimal number in JavaScript
 »   How to validate an email address in JavaScript
 »   How to validate date using JavaScript
 »   JavaScript String functions
 »   How to validate multiple select list box in JavaScript
 »   How to generate random numbers in JavaScript
 »   How to validate multiple check box in JavaScript
 »   How to validate user login in JavaScript
 »   How to validate drop down list in JavaScript
 »   How to validate radio button group in JavaScript
 »   How to create JavaScript alerts
 »    How to create popup windows in JavaScript
 »   How to count words in a text area using JavaScript




©-Copyright By Duminda Chamara   
JavaScript Validation  

How to create a popup window


How to Create a Popup window?




Following example shows you how to create a popup window in your web application.





Popup window is a separate browser window opens when user clicks on a link or a button. Also you can create a popup window when onload event of a web page. In most cases popup window is generally smaller than the main browser window. A popup window can open programmatically, using javascript. Popup windows are useful when displaying additional information, without make the page refresh or keeping the visitor on the same page, instead of redirected to an another page. When displaying Privacy Policy information or related help topic, you can use popup windows.



Popup windows doesn't have all features of a normal browser window. You can on off toolbars, status bars, scrollbars, change the window placement, change width and height of the popup window. Also you can make full screen popup windows. Not also that but also you can create re sizable popup windows or popup windows that user cannot resize.



Demo- Create Popup Windows Using JavaScript.

» Click on the button or link to

create an empty popup window.
    Simple Popup
         
» Click on the button or link to

create a popup window that opens a URL.
    Create Popup
         
» Click on the button or link to create a

re sizable popup window with status bar,

scrollbars, menu bars and toolbars.
    Create Popup
         
» Create customizable popup window      

Popup window width  

pixel
Popup window height  

pixel
Left alignment of the popup window  

pixel
Top alignment of the popup window  

pixel
Should popup window has scrollbars  
Should popup window has status bar  
Should popup window has toolbar  
Should popup window can re sizable  
Should popup window has menu bar  
Should popup window display in full screen  
URL that you want to open in popup window  
   
Copy following generated code in to a Notepad and
save it as 'popup.html' and open it.
Create Popup
         
         
» Create a popup window with custom content.

You can create a popup window that contains any kind of HTML elements

such as buttons, text boxes, etc. You can also add a close button to close the popup window.
         
      Create Popup


* Please note you have to turn off popup blocker in your browser to test this example.

Some features may not work in some browsers.



Bookmark and Share



Try It!









1. Example code for create an empty popup window.

JavaScript Code

<script type="text/javascript" language="javascript">

<!--

function createSimplePopupWindow(){

var popup=window.open('', 'Title', 'width=350,height=350,left = 412,top = 284');return false;

}

-->

</script>

HTML Code


<html>

<head><title>How to create a simple popup window </title>

</head><body>

<table border="0"><tr>

<td>&nbsp;<input name="btnPopupWindow1" type="submit" id="btnPopupWindow1" onclick="javascript:createSimplePopupWindow();" value="Simple Popup" /></td>

<td>&nbsp;</td>

<td><a href="javascript:void(0)" onclick="javascript:createSimplePopupWindow();" >Simple Popup</a></td></tr>

</table>

</body>

</html>




2. Example code for create a popup window that opens a URL.

JavaScript Code

<script type="text/javascript" language="javascript">

<!--

function createPopupWithURL(){

var popup=window.open('http://www.google.com', 'Google', 'width=350,height=350,left = 412,top = 284');return false;

}

-->

</script>

HTML Code


<html>

<head><title>How to create a popup window with URL </title>

</head><body>

<table border="0"> <tr>

<td>&nbsp;<input name="btnPopupWindow1" type="submit" id="btnPopupWindow1" onclick="javascript:createPopupWithURL();" value="Create Popup" /></td>

<td>&nbsp;</td>

<td><a href="javascript:void(0)" onclick="javascript:createPopupWithURL();" >Create Popup</a></td></tr>

</table>

</body>

</html>




3. Example code for create a
re sizable popup window

with status bar,
scrollbars, menu bars and toolbars.

JavaScript Code

<script type="text/javascript" language="javascript">

<!--

function createPopup(){

window.open('http://www.google.com','Google','toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=400,height=400,left=280,top= 100');return false;

}

-->

</script>

HTML Code


<html>

<head><title>How to create a popup window </title>

</head><body>

<table border="0"> <tr>

<td>&nbsp;<input name="btnPopupWindow1" type="submit" id="btnPopupWindow1" onclick="javascript:createPopup();" value="Create Popup" /></td>

<td>&nbsp;</td>

<td><a href="javascript:void(0)" onclick="javascript:createPopup();" >Create Popup</a></td></tr>

</table>

</body>

</html>




4. Example code for create a
popup window with custom content.

JavaScript Code

<script type="text/javascript" language="javascript">

<!--

function createCustomContentPopupWindow(){

var popup= window.open('','Google','width=350,height=180,left=412,top=284');

popup.document.write('<html><head><title>Simple Popup Window</title></head><body><table border="0">');

popup.document.write('<tr><td><h1 style="color:#FF9900;text-align:center">Hello!</h1>');

popup.document.write('<h4 style="color:#0000E6;text-align:center;">');

popup.document.write('Now you can create any kind of popup window.</h4></td></tr>');

popup.document.write('<tr><td>&nbsp;</td></tr><tr><td align="right">');

popup.document.write('<input name="btnClose" type="submit" id="btnClose" value="Close"');

popup.document.write('onclick="javascript:self.close();" /></td></tr></table></body></html>');

return false;

}

-->

</script>

HTML Code


<html>

<head><title>How to create a popup window with custom content</title>

</head><body>

<table border="0"> <tr>

<td>&nbsp;<input name="btnPopupWindow1" type="submit" id="btnPopupWindow1" onclick="javascript:createCustomContentPopupWindow();" value="Create Popup" /></td>

<td>&nbsp;</td>

<td><a href="javascript:void(0)" onclick="javascript:createCustomContentPopupWindow();" >Create Popup</a></td></tr>

</table>

</body>

</html>






 »   How to get screen resolution in JavaScript
 »   How to limit characters in textarea using JavaScript
 »   How to validate decimal number in JavaScript
 »   How to validate an email address in JavaScript
 »   How to validate date using JavaScript
 »   JavaScript String functions
 »   How to validate multiple select list box in JavaScript
 »   How to generate random numbers in JavaScript
 »   How to validate multiple check box in JavaScript
 »   How to validate user login in JavaScript
 »   How to validate drop down list in JavaScript
 »   How to validate radio button group in JavaScript
 »   How to create JavaScript alerts
 »    How to create popup windows in JavaScript
 »   How to count words in a text area using JavaScript



©-Copyright By Duminda Chamara   
JavaScript Validation  

Sunday, February 7, 2010

How to count words in a text area


How to count words in a textarea in JavaScript?




Following example shows you how to count number of words in a textarea using javascript.




In some cases you may need to count/get number of words in a textarea or text box. As an example You may need to limit number of words in a description (such as user comment or other description in your web application). Using following javascript you can count number of words in a textarea or a text box.



Demo- Count number of words in a textarea or text box using JavaScript.
How to Count words in a textarea.
Enter your description


Enter some text in the given textarea above, then click on Count Words to get the number of words you have entered. There are two additional option to remove one letter words and count 'a', 'an', 'the' as words or not.


Try It!

Bookmark and Share










1. Example code for get/count the number of words in a textare or a text box.

JavaScript Code
<script type="text/javascript" language="javascript">

<!--

function wordCounter(textField){

var text=document.getElementById(textField).value;

var words=text.split(' ');

var numberOfWords=words.length;

var countOneLetterWords=document.getElementById("checkIgnoreOneLetterWord").checked;

var countStandardWords=document.getElementById("countStandardWords").checked;



for(var i=0;i<words.length;i++){

var currentWord=words[i];

//alert(currentWord);

if(currentWord==""){

numberOfWords--;

}

if(countOneLetterWords==true && countStandardWords==true){

if(currentWord.length==1){

if(currentWord.toLowerCase()!="a"){//count 'a' as a word

numberOfWords--;

}

}

}else if(countOneLetterWords==false && countStandardWords==false){

//ignore 'a' 'an' 'the' as words

switch(currentWord.toLowerCase()){

case "a":{numberOfWords--;}break;

case "an":{numberOfWords--;}break;

case "the":{numberOfWords--;}break;

default:{}break;

}

}else if(countOneLetterWords==true && countStandardWords==false){

if(currentWord.toLowerCase()=="a"){//ignore 'a' as a word

numberOfWords--;

}else{

switch(currentWord.toLowerCase()){

case "a":{numberOfWords--;}break;

case "an":{numberOfWords--;}break;

case "the":{numberOfWords--;}break;

default:{}break;

}

}

}

}



alert("Number of words in your text = "+numberOfWords);

return true;

}

-->

</script>
HTML Code
<html>

<head><title>How to count Words in a text box or a textarea</title>

</head><body>

<table>

<tr>

<td colspan="3" align="left"><span class="demo_title"><a name="label_1" id="label_1"></a></span>1. Count words in a textarea. </td>

</tr>

<tr>

<td align="right">Enter your description </td>

<td align="left"><label>

<textarea name="txtWordCounter" cols="40" rows="8" id="txtWordCounter" title="Enter a decimal number here"></textarea>

</label></td>

<td>&nbsp;</td>

</tr>

<tr>

<td>&nbsp;</td>

<td align="left"><label>

<input name="checkIgnoreOneLetterWord" type="checkbox" id="checkIgnoreOneLetterWord" value="1" />

Ignore one letter words/characters as a word. </label></td>

<td align="left">&nbsp;</td>

</tr>

<tr>

<td>&nbsp;</td>

<td align="left"><label>

<input name="countStandardWords" type="checkbox" id="countStandardWords" value="1" checked="checked" />

Count 'a'. 'an', 'the' as words. </label></td>

<td align="left">&nbsp;</td>

</tr>

<tr>

<td>&nbsp;</td>

<td align="left"><input name="btnDecimalNumberValidator" type="submit" id="btnDecimalNumberValidator" onclick="javascript:wordCounter('txtWordCounter');" value="Count Words" title="Click here to validate" /></td>

<td align="left">&nbsp;</td>

</tr>

<tr>

<td colspan="3">&nbsp;</td>

</tr>

</table>

</body>

</html>
 







 »   How to get screen resolution in JavaScript
 »   How to limit characters in textarea using JavaScript
 »   How to validate decimal number in JavaScript
 »   How to validate an email address in JavaScript
 »   How to validate date using JavaScript
 »   JavaScript String functions
 »   How to validate multiple select list box in JavaScript
 »   How to generate random numbers in JavaScript
 »   How to validate multiple check box in JavaScript
 »   How to validate user login in JavaScript
 »   How to validate drop down list in JavaScript
 »   How to validate radio button group in JavaScript
 »   How to create JavaScript alerts
 »    How to create popup windows in JavaScript
 »   How to count words in a text area using JavaScript


©-Copyright By Duminda Chamara
JavaScript Validation