Search This Blog
2009-05-27
Parsing Querystring using Javascript
Suppose we are going to pass the name and email from the parent or source page as the query string and the destination page supposed to be "parseQueryString.htm".
From the Parent page or the source page write the following code
<input type="text" name="txtName" id="txtName">Name<br>
<input type="text" name="txtEmail" id="txtEmail">Email<BR>
<input type="button" value="Submit" onclick="getURL(txtName.value, txtEmail.value);">
<script>
function getURL(sName, sEmail){
window.location ="parseQueryString.htm?name="+sName+"&email="+sEmail;
}
</script>
In the destination page "parseQueryString.htm" write the following code and call it from body onload as follows
<script>
function PageQuery(q) {
if(q.length > 1) this.q = q.substring(1, q.length);
else this.q = null;
this.keyValuePairs = new Array();
if(q) {
for(var i=0; i < this.q.split("&").length; i++) {
this.keyValuePairs[i] = this.q.split("&")[i];
}
}
this.getKeyValuePairs = function() { return this.keyValuePairs; }
this.getValue = function(s) {
for(var j=0; j < this.keyValuePairs.length; j++) {
if(this.keyValuePairs[j].split("=")[0] == s)
return this.keyValuePairs[j].split("=")[1];
}
return false;
}
this.getParameters = function() {
var a = new Array(this.getLength());
for(var j=0; j < this.keyValuePairs.length; j++) {
a[j] = this.keyValuePairs[j].split("=")[0];
}
return a;
}
this.getLength = function() { return this.keyValuePairs.length; }
}
function queryString(key){
var page = new PageQuery(window.location.search);
return unescape(page.getValue(key));
}
function displayItem(key){
if(queryString(key)=='false')
{
result.innerHTML="you didn't enter a ?name=value querystring item.";
}else{
result.innerHTML+=queryString(key)+"<BR>";
}
}
</script>
<body onload="displayItem('name'); displayItem('email');">
<div id=result></div>
</body>
2009-05-19
Javascript YES NO Confirm Dialog
You can do it by the following code.
Write the following code in the head section of your HTML Page
<script language="javascript" type="text/javascript">
/*@cc_on @*/
/*@if (@_win32 && @_jscript_version>=5)
function window.confirm(str)
{
execScript('n = msgbox("'+str+'","4132")', "vbscript");
return(n == 6);
}
@end @*/
</script>
Call the function from the onClientClick event of your button
<asp:Button ID="btnOk" runat="server" OnClientClick="javascript:return confirm('Are you sure to proceed?');" OnClick="btnOk_Click" Text="OK" />
Write the btnOk_Click event in your server side code
protected void btnOk_Click(object sender, EventArgs e)
{
Response.Write("User Click Yes");
}
Now run your application,click the "OK" button.You can see a Yes NO Dialog Box,if the user click yes the control will go to the server side method,if the user click no,the Server side code will not execute
You can change the Dialog as OK Cancel by changing the value 4132 to 4129 in the statement execScript('n = msgbox("'+str+'","4132")', "vbscript");
For Abort Rety Ignore change the value to 4130
For yes no cancel change the value to 4131
For Retry Cancel ,Change the value to 4133
For OK Change the value to 4134
The @cc_on statement activates conditional compilation in the scripting engine.
It is strongly recommended that you use the @cc_on statement appear in a comment, so that browsers that do not support conditional compilation will accept your script as valid syntax:
//@cc_on
...
(remainder of script)
Alternatively, an @if or @set statement outside of a comment also activates conditional compilation.
2009-05-14
Disable Back Button in the browser
<script language="javascript" type="text/javascript">
window.onload=onLoadFunctions;
function onLoadFunctions()
{
backButtonOverride();
}
function backButtonOverride()
{
setTimeout("backButtonOverrideBody()", 0);
}
function backButtonOverrideBody()
{
try {
history.forward();
}
catch (e)
{
// OK to ignore
}
setTimeout("backButtonOverrideBody()", 0);
}
</script>
2009-04-27
Multi select Dropdown control
Code:
Step 1.Create an HTML file and copy the following HTML code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>MultiSelect Dropdown List</TITLE>
<SCRIPT Language="javaScript">
function ShowList(textID,fieldid){
if(document.getElementById(fieldid).style.display == 'none') //if the dropdown is not displayed, display the dropdown below the textbox.
{
document.getElementById(fieldid).style.display = 'inline';
var lsobj=document.getElementById(textID);
var lscurleft = 0;
var lscurtop = 0;
if (lsobj.offsetParent) {
do {
lscurleft += lsobj.offsetLeft;
lscurtop += lsobj.offsetTop;
} while (lsobj = lsobj.offsetParent);
}
document.getElementById(fieldid).style.left=lscurleft;
document.getElementById(fieldid).style.top=lscurtop + 22;
}
else
{
document.getElementById(fieldid).style.display = 'none';
}
}
function HideDropdown(fieldname,textfield,hiddenfield)
{
var lsnewStr="";
var lsnewVal="";
var lsCurrentSelectedvalue=document.frmMultiSelect[fieldname].value;
var lsCurrentSelected= document.frmMultiSelect[fieldname].options[document.frmMultiSelect[fieldname].selectedIndex].text;
lsCurrentSelected = lsCurrentSelected.replace(/^\s+\s+$/, ''); // used to trim the selected text in the dropdown
var lsSelectedDisplayValues= document.frmMultiSelect[textfield].value;
var lsSelectedValue= document.frmMultiSelect[hiddenfield].value;
if(lsSelectedDisplayValues.indexOf(lsCurrentSelected) == -1) // if the selected item is not selected earlier
{
document.frmMultiSelect[textfield].value+=lsCurrentSelected + ";";
document.frmMultiSelect[hiddenfield].value+=lsCurrentSelectedvalue + ";";
}
else // if the current selected item is already selected, it removes the current selected item in the list displayed in the text box
{
document.frmMultiSelect[textfield].value=lsSelectedDisplayValues.replace(lsCurrentSelected + ";","");
document.frmMultiSelect[hiddenfield].value=lsSelectedValue.replace(lsCurrentSelectedvalue + ";","");
}
var larr_col=document.frmMultiSelect[textfield].value.split(";"); // splits the value in the hidden field in to an aray list
var larr_col_text = document.frmMultiSelect[hiddenfield].value.split(";"); // splits the value in the textbox field in to an aray list
document.frmMultiSelect[fieldname].selectedIndex = -1;
var i;
<!--- the following loop is helps to select the selected items in the dropdown programatically --->
for(i=0;i<=document.frmMultiSelect[fieldname].length-1;i++) // loop through the entire list in the select dropdown
{
var lspart_num=0;
while (lspart_num < larr_col.length-1)
{
if(document.frmMultiSelect[fieldname].options[i].value==larr_col_text[lspart_num])
{
var lstemp = document.frmMultiSelect[fieldname].options[i].text;
lstemp = lstemp.replace(/^\s+\s+$/, ''); // trims the leading spaces for the selected item
lsnewStr+= lstemp+";"; // this variable stores the dispalyed text of the selected items in the dropdown
document.frmMultiSelect[fieldname].options[i].selected = true;
lsnewVal+= document.frmMultiSelect[fieldname].options[i].value+";"; //this variable stores the value of the selected items in the dropdown
}
lspart_num++;
}
}
document.frmMultiSelect[textfield].value = lsnewStr;
document.frmMultiSelect[hiddenfield].value = lsnewVal;
}
</SCRIPT>
</Head>
<BODY LINK="#3300FF" ALINK="#3300FF" VLINK="#3300FF">
<FORM NAME="frmMultiSelect" ACTION="" METHOD="Post">
<TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="0">
<TR>
<TD ALIGN="CENTER">
<SPAN STYLE="">SELECT MULTIPLE VALUES IN A DROPDOWN LIST WITHOUT USING CTRL KEY</SPAN>
</TD>
</TR>
<TR><TD> </TD></TR>
<TR>
<TD ALIGN="CENTER">
<SPAN><B>Select Country:</B></SPAN>
<INPUT TYPE="hidden" NAME="hdnCountryValue" VALUE="">
<!--- hidden field is used to hold the values of the selected items in the dropdown. Useful when the value of the items in the dropdown is different than the displayed text for each item in the dropdown. --->
<INPUT TYPE="text" NAME="txtCountryText" READONLY STYLE="Width:280px;" VALUE="" ONCLICK="Javascript:ShowList('txtCountryText','CountryId')"><IMG SRC="./DropDown.bmp" ALIGN="Top" ONCLICK="Javascript:ShowList('txtCountryText','CountryId')">
<!--- ShowList function is used to display and hide the select dropdown list when the textbox or the image is clicked. HideDropDown function selects or deselects the items in the dropdown list --->
<DIV STYLE="Z-INDEX:1;POSITION:absolute;DISPLAY:none;" ID="CountryId">
<SELECT MULTIPLE="Yes" NAME="cboCountry" STYLE="Width: 300px;" SIZE="6" onChange="Javascript:HideDropdown('cboCountry', 'txtCountryText','hdnCountryValue')" onBlur = "Javascript:ShowList('txtCountryText','CountryId')">
<OPTION selected value=""></OPTION>
<OPTION VALUE="Afghanistan">Afghanistan</OPTION>
<OPTION VALUE="Albania">Albania</OPTION>
<OPTION VALUE="Algeria">Algeria</OPTION>
<OPTION VALUE="Antarctica">Antarctica</OPTION>
<OPTION VALUE="Argentina">Argentina</OPTION>
<OPTION VALUE="Australia">Australia</OPTION>
</SELECT>
</DIV>
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
Step 2.Put the following image file in the folder where you keep your HTML File.Be sure that the image name is "DropDown.bmp"
Accessing Server side values from client Side
Method 1:-Acessing Client side values by HiddenField
In the HTML page ,write the following javascrpit function in the head section
<script type="text/javascript">
function getSharedData()
{
//Display value of hidden field.
alert("Shared data is " + document.getElementById("sharedData").value + ".");
//Change value of hidden field.
document.getElementById("sharedData").value="A new value";
}
</script>
Take a HiddenField and a button in the Body ,call the function getSharedData() from the OnCLientClick Event of the button
<asp:HiddenField ID="sharedData" runat="server" Value="Shared Data" />
<div>
<asp:Button ID="btnGetData" runat="server" Text="Get Data" OnClientClick="getSharedData()" />
From the server side code write the following code to get the values of hidden feild which are assigned from the javascript.
protected void Page_Load(object sender, EventArgs e)
{
//Access value of hidden field from client.
String test = sharedData.Value;
}
Method 2.Dynamically create a hidden field on the client
Keep the HTML code as it is in Method 1.
Modify the server side code as follows
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager csm = Page.ClientScript;
//Use ClientScriptManager to dynamically create a hidden field on the client.
String hiddenName = "sharedData";
String hiddenValue = "Client data value";
//This hidden field is not a server side control, just a hidden <input> element on the client.
csm.RegisterHiddenField(hiddenName, hiddenValue);
}
Method 3:Create a HiddenField server control programmatically
Keep the HTML code as it is in Method 1.
Modify the server side code as follows
protected void Page_Load(object sender, EventArgs e){
//Create a HiddenField server control programmatically.
System.Web.UI.WebControls.HiddenField hiddenField = new System.Web.UI.WebControls.HiddenField();
hiddenField.ID = "sharedData";
hiddenField.Value = "New client initial value on Page 3";
//Important to add the control to the Form not the Page.
Page.Form.Controls.Add(hiddenField);
}
Method 4:Create and dynamically register an array on the server
Keep the HTML code as it is in Method 1. and modify the getSharedData() function from in the Client Side javascrpit.
function getSharedData()
{
//Display the 5th element of the array, "5".
alert("Shared data is " + sharedData[4] + ".");
}
In the server side code make the following modifications.
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager csm = Page.ClientScript;
//Create and dynamically register an array on the server that is rendered in the JavaScript on the client.
String arrayName = "sharedData";
String arrayValues = "1,2,3,4,5";
csm.RegisterArrayDeclaration(arrayName, arrayValues);
}
2009-04-17
Server side Message box when Ajax is using
When Ajax Content is using ,it is too tough to show a javascript alert message box from the server side in the webpage.Following function to show message box in Ajax update panel.
Step 1.
Create a Class file name named as WebMsgBox.cs
Step 2.
Copy the follwoing code in that cs file
using System;
using Microsoft.VisualBasic;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestWebMsgApp
{
public class WebMsgBox
{
protected static Hashtable handlerPages = new Hashtable();
private WebMsgBox()
{
}
public static void Show(string Message)
{
if (!(handlerPages.Contains(HttpContext.Current.Handler)))
{
Page currentPage = (Page)HttpContext.Current.Handler;
if (!((currentPage == null)))
{
Queue messageQueue = new Queue();
messageQueue.Enqueue(Message);
handlerPages.Add(HttpContext.Current.Handler, messageQueue);
currentPage.Unload += new EventHandler(CurrentPageUnload);
}
}
else
{
Queue queue = ((Queue)(handlerPages[HttpContext.Current.Handler]));
queue.Enqueue(Message);
}
}
private static void CurrentPageUnload(object sender, EventArgs e)
{
Queue queue = ((Queue)(handlerPages[HttpContext.Current.Handler]));
if (queue != null)
{
StringBuilder builder = new StringBuilder();
int iMsgCount = queue.Count;
builder.Append("<script language='javascript'>");
string sMsg;
while ((iMsgCount > 0))
{
iMsgCount = iMsgCount - 1;
sMsg = System.Convert.ToString(queue.Dequeue());
sMsg = sMsg.Replace("\"", "'");
builder.Append("alert( \"" + sMsg + "\" );");
}
builder.Append("</script>");
handlerPages.Remove(HttpContext.Current.Handler);
HttpContext.Current.Response.Write(builder.ToString());
}
}
static public void DisplayAJAXMessage(Control page, string msg)
{
string myScript = String.Format("alert('"+ msg +"');",msg);
//string myScript = String.Format("alert('"{0}"');",msg);
ScriptManager.RegisterStartupScript(page, page.GetType(),
"MyScript", myScript, true);
}
}
}
Step 3.
Now call the method show from the CS file of your webpage
TestWebMsgApp.WebMsgBox.Show("Hello");
Now you can see the server side message box in the web page when ajax is using
ASP.NET Treeview checkbox with select all
It is very easy to create a checkbox with the ASP.NET treeview by the property
ShowCheckBoxes="All".Suppose yoy have a two or three level nodes in the tree hierarchy.You want to select the parent node & you like to select all the child node chekbox to be selected automatically.De selecting any of the child node,the parent node will be deslected but the remaining other child nodes will be remain same.Following are the solution of this problem.
Step 1.
Create a javascript file & save it as a TreeViewCheckUncheck.js.
// JScript File
function OnTreeClick(evt)
{
//alert(evt);
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var isChkBoxClick = (src.tagName.toLowerCase() == "input" && src.type == "checkbox");
if(isChkBoxClick)
{
//alert(src.value);
var parentTable = GetParentByTagName("table", src);
var nxtSibling = parentTable.nextSibling;
//check if nxt sibling is not null & is an element node
if(nxtSibling && nxtSibling.nodeType == 1)
{
if(nxtSibling.tagName.toLowerCase() == "div")
//if node has children
{
//check or uncheck children at all levels
CheckUncheckChildren(parentTable.nextSibling, src.checked);
}
}
//check or uncheck parents at all levels
CheckUncheckParents(src, src.checked);
}
}
function CheckUncheckChildren(childContainer, check)
{
var childChkBoxes = childContainer.getElementsByTagName("input");
var childChkBoxCount = childChkBoxes.length;
for(var i=0;i<childChkBoxCount;i++)
{
childChkBoxes[i].checked = check;
}
}
function CheckUncheckParents(srcChild, check)
{
var parentDiv = GetParentByTagName("div", srcChild);
var parentNodeTable = parentDiv.previousSibling;
if(parentNodeTable)
{
var checkUncheckSwitch;
if(check) //checkbox checked
{
var isAllSiblingsChecked = AreAllSiblingsChecked(srcChild);
if(isAllSiblingsChecked)
checkUncheckSwitch = true;
else
return; //do not need to check parent if any(one or more) child not checked
}
else //checkbox unchecked
{
checkUncheckSwitch = false;
}
var inpElemsInParentTable = parentNodeTable.getElementsByTagName("input");
if(inpElemsInParentTable.length > 0)
{
var parentNodeChkBox = inpElemsInParentTable[0];
parentNodeChkBox.checked = checkUncheckSwitch; //do the same recursively
CheckUncheckParents(parentNodeChkBox, checkUncheckSwitch);
}
}
}
function AreAllSiblingsChecked(chkBox)
{
var parentDiv = GetParentByTagName("div", chkBox);
var childCount = parentDiv.childNodes.length;
for(var i=0;i<childCount;i++)
{
if(parentDiv.childNodes[i].nodeType == 1)
{
//check if the child node is an element node
if(parentDiv.childNodes[i].tagName.toLowerCase() == "table")
{
var prevChkBox = parentDiv.childNodes[i].getElementsByTagName("input")[0];
//if any of sibling nodes are not checked,
return false
if(!prevChkBox.checked)
{
return false;
}
}
}
}
return true;
}
//utility function to get the container of an element by tagname
function GetParentByTagName(parentTagName, childElementObj)
{
var parent = childElementObj.parentNode;
while(parent.tagName.toLowerCase() != parentTagName.toLowerCase())
{
parent = parent.parentNode;
}
return parent;
}
Step 2.Call this javascript file from the particular location
<script src="../Javascript/TreeViewCheckUncheck.js" language="javascript" type="text/javascript"></script>
Step 3. Create a ASP.NET treeview and bind it to your datasource .call the javascript function from onClick event of the treeview as follows.
<asp:TreeView ID="TreeView1" NodeStyle-CssClass="treeview" runat="server" ShowCheckBoxes="All"
DataSourceID="XmlDataSource1" onClick="javascript:OnTreeClick(event);">
<HoverNodeStyle CssClass="treeview" />
<NodeStyle CssClass="treeview" />
<DataBindings>
<asp:TreeNodeBinding SelectAction="None" PopulateOnDemand="true" Value="ID" ValueField="ID"
TextField="Name"></asp:TreeNodeBinding>
</DataBindings>
</asp:TreeView>
Output:
2009-04-16
ASP Treview Checkbox Work as Radiobutton
You can find several example where treeview checkbox work as a radio button.In most of the examples have a common problem.As long as there is no checkbox in the page except the checkbox in the treeview, they work fine,but if you have another checkbox or another treeview which contains checkbox,then the problem arises.When click on the treeview checkbox,they(that function) uncheck all of the checkboxs in the page which is not desire.The following function overcomes that problem.
Step 1.
Create a ASP treeview in the HTML & Bind it to your datasource
<asp:TreeView ID="mnuLocationFilter" NodeStyle-CssClass="treeview" runat="server"
ShowCheckBoxes="All" DataSourceID="XmlDsMnuLocationFilter">
<HoverNodeStyle CssClass="treeview" />
<NodeStyle CssClass="treeview" />
<DataBindings>
<asp:TreeNodeBinding SelectAction="None" PopulateOnDemand="true" Value="ID" ValueField="ID"
TextField="Name"></asp:TreeNodeBinding>
</DataBindings>
</asp:TreeView>
Step 2.
Copy the following function in the javascript portion of the HTML Page
function client_OnTreeNodeChecked_ucSelectSeason(event,treeName)
{
var TreeNode =event.srcElement event.target ;
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
if (TreeNode.tagName == "INPUT" && TreeNode.type == "checkbox")
{
if(TreeNode.checked)
{
uncheckOthers_ucSelectSeason(TreeNode.id,src,treeName);
}
}
}
function uncheckOthers_ucSelectSeason(id,src,treeName)
{
var elements = document.getElementsByTagName('input');
// loop through all input elements in form
for(var i = 0; i < elements.length; i++) { if(elements.item(i).type == "checkbox") { if(elements.item(i).id!=id) { if(elements.item(i).id.indexOf(treeName)>0)
{
elements.item(i).checked=false;
}
}
}
}
}
Step 3.
In the pageload event of the codebehind write the following code
Treeview1.Attributes.Add("OnClick", "client_OnTreeNodeChecked_ucSelectSeason(event,'Treeview1')");
