Friday, August 28, 2009

Javascript Arrays Syntax and Examples

Please visit my new Web Site

For each programming language array is a most common & popular object. Without array most of the times we can not make our logic. Thats why in this post i will try to give you a complete article on Javascript arrays, syntax with appropriate code examples. We knew that variables are used to store a single piece of information in the memory. Where as array can hold a series of information as its elements. So that you can retrieve value by providing a single name with an element number. Think you have to take 15 numeric inputs from user then apply some logic & generate the output. So it will be cumbersome to think of a variable name for each of input. Such type of problem you can overcome by using array. So we can write the definition of an array is "An array is also a variable of a sequence, or list, of values. A value in a JavaScript array can hold a number or string, function or an object. JavaScript arrays can store any datatype. A single value in a JavaScript array will be treated an element." In the later section of the article i will also discuss on "Javascript Dynamic Array Syntax and Declaration" and "Predefined or Builtin Javascript Array Functions".

Syntax of an Array:
Every array has to be declared before using it. In Javascript array declaration syntax is geven below:
var thearrayname=new Array(arraylength)

In the above syntax thearrayname is a variable like array. We can create an array only using the syntax new Array. It's case sensitive and so "Array" should not be defined as "array". You can declare the size of the array in arraylength. So, we can store variables in the array that we have declared as arraylength. You can declare any size based on your requirement.

Declaring & Assigning Values:
So based on above syntax now we want to declare an array of size 4. Which will hold our favourite colors name. So the declaration will be:
var favColor=new Array(4);

Now we need to assign our favourite colors name:

Look at the assignment here you found that i have started from 0. Because Arrays always start from 0th index or position. If we have set the size as 4, the array will have 4 position 0,1,2 & 3.

You can also declare in the following way:
var favColor=new Array("White","Red","Green","Yellow");

Such arrays are known as "Dense Arrays". They are declared by listing the values of the arrau elements in the declaration, in place of the array length.

Few Concern:
1. You can define any element values in any order.
2. You can increase the array length any time.
3. IF you want to assign a value in out range of array index, the value will be discarded.

Retrieving Values:
We have learned how we can stroe values in an array. Now we will learn how we can read values from array. There were two ways we can read values. One is directly calling by index number & another one is looping through array.

Now if you want to print your 4th favourite color name then the code should be:
document.write("My favourite color is : "+favColor[3]);

Now if you want to loop through the array & print all values then the code should be:

var favColor=new Array(4);


//To get the length of an javascript array, use its length property
var len=favColor.length;
document.write("My favourite color "+eval(i+1)+" is :"+favColor[3]);

So i think the basic concept on javascript array is clear now. Now we can move forward for more on arrays.

Javascript Dynamic Array Syntax And Declaration:
In most of the times during logic building we do not want to mention or specify the array with a fixed size or length. In such cases we can create or declare an array with out mentioning the length. This array will dynamically set its value when a new variable or entry is added.

var thearrayname= new Array();

Now we can assign value at any position in this array as it has no length specified. We can test this by using the attribute "length".e.g:
thearrayname[3] = "Yellow";

As we have assigned a value in 3rd position the length of array will now be 4.

Javascript Arrays Builtin Functions:
The following are some standard functions that can be used only with arays:

This function converts an array to a string. Commas separate the array elements.

This function is same as the toString() function. It converts an array to a string, but the seperator string separates the array elements.

This function sorts the contents of an array based upon the ASCII value.

This function reverses the contents of an array. The last element becomes first and the first elements becomes last.

The basic syntax for using the above function is as follows:

The following example shows how to use the various standard array functions:
Usage of javascript array built in functions
<body style="font-family:verdana;font-size:1.2em">
<h1>List of builtin javascript array functions</h1>
<script language="JavaScript">
var favColor=new Array(4)
document.write("favColor.toString() : "+favColor.toString()+"<br/><br/>");
document.write("favColor.join('') : "+favColor.join('')+"<br/><br/>");
document.write("favColor.reverse() : "+favColor.reverse()+"<br/><br/>");
document.write("favColor.sort() : "+favColor.sort()+"<br/><br/>");

This program uses the toString(), reverse(), sort() and join() functions to manipulate the contents of the array favColor.

Create autogenerate serial number column in GridView

Please visit my new Web Site

In many forums i found the question "How to generate a column as serial number at runtime of a gridview?". Also they have another concern was paging. Thats why here i want to share a simple code snippet with all. Which will help you to add a autogenerate number or sequential number or serial number in your GridView with less effort. Mind it the serial number will not come from Database. We will generate automatically in runtime or in design time. No extra server side code is required.

Fig: Output

To do that just add a GridView control in your aspx page. Then create a TemplateField column in the GridView and add Container.DisplayIndex+1 as inline code. Will generate your required output. Here i will show you step by step code. Hope you don't need to write a line of code. Just copy my codes step by step. After that run your project.

GridView HTML Code:
<b>List of suppliers:</b>

<asp:GridView runat="server" ID="gvEdit">

<asp:TemplateField HeaderText="S.No">
<%# Container.DisplayIndex + 1 %>

<asp:BoundField DataField="Code" HeaderText="Code">
<asp:BoundField DataField="Name" HeaderText="Name">
<asp:BoundField DataField="Address" HeaderText="Address">
<asp:BoundField DataField="Contact" HeaderText="Contact no">

Populate or Bind GridView with sample Data:
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
DataTable dtSupplier = new DataTable("Supplier");
dtSupplier.Columns.Add(new DataColumn("ID", System.Type.GetType("System.UInt64")));
dtSupplier.Columns.Add(new DataColumn("Code"));
dtSupplier.Columns.Add(new DataColumn("Name"));
dtSupplier.Columns.Add(new DataColumn("Address"));
dtSupplier.Columns.Add(new DataColumn("Contact"));
dtSupplier.Rows.Add(1, "st0001", "S.R. Steel", "Uttara, Dhaka", "01711xxxxxx");
dtSupplier.Rows.Add(2, "ir0039", "Shadesh builders", "Rampura, Dhaka", "01711yyyyyy");
dtSupplier.Rows.Add(3, "cr0042", "Orchard confec.", "Shahabag, Dhaka", "01711zzzzzz");
dtSupplier.Rows.Add(4, "er0078", "Windblow", "Mirpur, Dhaka", "01711qqqqqq");
dtSupplier.Rows.Add(5, "bd0301", "Rahimkarim", "Badda, Dhaka", "01711oooooo");
gvEdit.DataSource = dtSupplier;

Now run your application. Hope you will see the serial number as a first column in your aspx page. No Database connectivity required here to ease the example. Also you can visit GridView & Asp.Net labels to read more.

Saturday, August 8, 2009

How to read asp radio button list selected value

Please visit my new Web Site

Using javascript to get the asp radio button list selected value is not an easy job like other objects. To get the selected value from asp radio button list you have to iterate through all the radio buttons in that set and then read the value for checked radio button. In my previous post i have discussed on DropdownList or ComboBox. So in this post i will try to give you a complete example on how we can read selected value or selected text from Asp RadioButtonList or from HTML input type="radio". So lets start. At first create a new aspx page. In this page i will add one Asp RadioButtonList & one HTML input type="radio" object. Also add two labels to display the Selected Value & Selected Text as well. Our targeted output should be:

If you are looking for Jquery solution then CLICK HERE.
The html code for the aspx page should be:
<form id="form1" runat="server">

<b>Asp Radio Button List:</b>
<hr />

<asp:RadioButtonList ID="Aspradiobuttonlist" runat="Server" RepeatDirection="vertical" onclick="GetRadioButtonSelectedValue();">
<asp:ListItem Text="Cosmetics" Value="1" Selected="True"></asp:ListItem>
<asp:ListItem Text="Perfume" Value="2"></asp:ListItem>
<asp:ListItem Text="Beauty Soap" Value="3"></asp:ListItem>
<asp:ListItem Text="Sunglasses" Value="4"></asp:ListItem>

<br />
<asp:Label runat="server" ID="lblAspradiobuttonValue"></asp:Label>


<b>HTML Radio Button List:</b>
<hr />

<input type="radio" name="Category" value="1" checked="checked" onclick="GetHTMLRadioButtonSelectedValue();">Cosmetics<br/>
<input type="radio" name="Category" value="2" onclick="GetHTMLRadioButtonSelectedValue();">Perfume<br/>
<input type="radio" name="Category" value="3" onclick="GetHTMLRadioButtonSelectedValue();">Beauty Soap<br/>
<input type="radio" name="Category" value="4" onclick="GetHTMLRadioButtonSelectedValue();">Sunglasses<br/>

<br />

<asp:Label runat="server" ID="lblHTMLradiobuttonValue"></asp:Label>


Ok now we have to add two javascript method for Asp RadioButtonList & HTML input type="radio" respectively.

Get Selected Value from Asp RadioButtonList:
<script type="text/javascript">

function GetRadioButtonSelectedValue()
var AspRadio = document.getElementsByName('Aspradiobuttonlist');

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

if (AspRadio[i].checked)
var lblAspradiobuttonValue = document.getElementById('<%= lblAspradiobuttonValue.ClientID %>');

lblAspradiobuttonValue.innerHTML='<b>Selected Value:</b> '+AspRadio[i].value+'<br/>';
lblAspradiobuttonValue.innerHTML+='<b>Selected Text:</b> '+AspRadio[i].parentNode.getElementsByTagName('label')[0].innerHTML;
}//end if

}// end for

}//end function


Get Selected Value from HTML Input Radio:
<script type="text/javascript">

function GetHTMLRadioButtonSelectedValue()
var HTMLRadio=document.form1.Category;

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

if (HTMLRadio[i].checked)
var lblHTMLradiobuttonValue = document.getElementById('<%= lblHTMLradiobuttonValue.ClientID %>');
lblHTMLradiobuttonValue.innerHTML='<b>Selected Value:</b> '+HTMLRadio[i].value+'<br/>';
lblHTMLradiobuttonValue.innerHTML+='<b>Selected Text:</b> '+HTMLRadio[i].parentNode.getElementsByTagName('label')[i].innerHTML;
}// end if

}// end for

} // end function


Script tested for below browsers:
1. Internet Explorer
2. Mozilla Firefox
3. Opera
4. Google Chrome

So now you can read the Selected value or Selected Text from both Asp RadioButtonList & HTML Input Radio by using above javascript method or function.

Thursday, August 6, 2009

Javascript How to get SelectedText from Asp Dropdownlist or HTML Select option

Please visit my new Web Site

asp:DropDownList is the server side control of & the drop down selection list is an element of HTML forms commonly know as Combo Box. Most of the times developers need to find or get the Selected Index value, Selected Value & Selected Text. In this post i will show you how one can write a cross-browser supported client side javascript to get Selected Index, Selected Text & Selected Value form server side control asp:DropDownList & HTML drop down selection list. Hope it will help & save time for developers. Click Here to read how to populate DropdownList. In this post this is the beyond of scope.

If you want Jquery solution then CLICK HERE.

Desired Output:

Fig: Shows the index no, selected value & selected text.

Get selected value of asp:dropdownlist in javascript:
So first add an aspx page into your project & paste the below HTML code for asp:dropdownlist under the form div section:
<form id="form1" runat="server">

<asp:Label runat="server" ID="Label1">
DropdownList</asp:Label><br />

<asp:DropDownList id="aspdropdown" runat="server" onchange="getDropdownListSelectedText();">

<asp:ListItem Value="Asp" Text="Free articles/Code examples"></asp:ListItem>
<asp:ListItem Value="Sqlserver" Text="Free Sql server articles/Code examples"></asp:ListItem>
<asp:ListItem Value="Javascript" Text="Free Javascript articles/Code examples"></asp:ListItem>
<asp:ListItem Value="XML" Text="Free XML articles/Code examples"></asp:ListItem>
<asp:ListItem Value="Gridview" Text="Free Gridview articles/Code examples"></asp:ListItem>


<asp:Label runat="server" ID="lblDropdownList"></asp:Label>


Now add the below client side cross browser javascript function under head tag:
<script type="text/javascript">
function getDropdownListSelectedText()
var DropdownList=document.getElementById('<%=aspdropdown.ClientID %>');
var SelectedIndex=DropdownList.selectedIndex;
var SelectedValue=DropdownList.value;
var SelectedText=DropdownList.options[DropdownList.selectedIndex].text;

var LabelDropdownList=document.getElementById('<%=lblDropdownList.ClientID %>');
var sValue='Index: '+SelectedIndex+' Selected Value: '+SelectedValue+' Selected Text: '+SelectedText;


Get Selected Value of HTML Select Option in javascript:
The HTML code for Combo Box is given below:
<form id="form1" runat="server">

<asp:Label runat="server" ID="Label2">HTML Select Option</asp:Label><br />

<select name="HTMLSelect" onchange="getHTMLSelectOptionText();">

<option value="Asp">Free articles/Code examples
<option value="Sqlserver">Free Sql server articles/Code examples
<option value="Javascript">Free Javascript articles/Code examples
<option value="XML">Free XML articles/Code examples
<option value="Gridview">Free Gridview articles/Code examples


<asp:Label runat="server" ID="lblSelectOptionText"></asp:Label>


Now add the below client side cross browser javascript function under head tag:
<script type="text/javascript">
function getHTMLSelectOptionText()
var SelectOption=document.form1.HTMLSelect;
var SelectedIndex=SelectOption.selectedIndex;
var SelectedValue=SelectOption.value;
var SelectedText=SelectOption.options[SelectOption.selectedIndex].text;

var LabelDropdownList=document.getElementById('<%=lblSelectOptionText.ClientID %>');
var sValue='Index: '+SelectedIndex+' Selected Value: '+SelectedValue+' Selected Text: '+SelectedText;


If you look at the javascript client side code you will found three different vaiables i have used to collect Selected Index, Selected Value & Selected Text value. You can use one of them which is required for you. Now you can do anything based on user selection such as write the selected text into textbox, populate another dropdownlist, Run sql server query for filtering purposes etc...

Script tested for below browsers:
1. Internet Explorer.
2. Mozilla Firefox
3. Opera
4. Google Chrome
Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash