Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Tuesday, November 24, 2009

"String Builder" function in Javascript using Ajax(Enabling Scriptmanager).

I have come across new functionality called "stringbuilder" in javascript using Ajax.

please follow the below steps to enable the Stringbuilder.

Step 1:

Add script manager tag in the aspx page.


Step 2:

Example:

<script type="text/javascript">
function buildAString(title)
{
var headTagStart = "";
var headTagEnd = "";
var titleTagStart = "";
var sb = new Sys.StringBuilder(this._headTagStart);
sb.append(titleTagEnd);
sb.append(title);
sb.append(titleTagEnd);
sb.append(headTagEnd);
// Displays: "The result: "
alert("The result" + sb.toString());
}
var title = "A Title";
buildAString(title);
</script>

Friday, October 9, 2009

Special Character Validation

var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?~_";

for (var i = 0; i < objGridCellValue.length; i++)
{
if (iChars.indexOf(objGridCellValue.charAt(i)) != -1) {
alert ("Your string has special characters. \nThese are not allowed.");
return false;
}
}

Date Compare Function

function DateFormat(dt)
{
var dtformat = new Date(dt)
return dt.format("MM/dd/yyyy");
}

function DateCompare(fromDt,toDt)
{
var arrFromdt=fromDt.split("/");
var arrTodt=toDt.split("/");
var fromDt=new Date(arrFromdt[2],replaceDt(arrFromdt[0]),replaceDt(arrFromdt[1]));
var toDt=new Date(arrTodt[2],replaceDt(arrTodt[0]),replaceDt(arrTodt[1]));
if(fromDt<=toDt)
{
return "1";
}
else
{
return "0";
}
}
function replaceDt(replaceValue)
{
if(parseInt(replaceValue)<10)
{
return replaceValue.replace('0','');
}
else
{
return replaceValue;
}
}

Friday, August 21, 2009

Asp DataGrid with Editable cell with out Postback using Javascript

This is created for one of my friend. he want's in his project. so i thought of sharing with everyone am writing in my blog.

step 1:

create asp grid control with binding dummy value.

step 2:

<asp:GridView ID="grView" runat="server" AutoGenerateColumns="false"
onprerender="grView_PreRender">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div id="lblDiv" runat="server">
<asp:Label ID="lblID" runat="server" Text='<%# Eval("Empid") %>'></asp:Label>
</div>
<div id="txtDiv" style="display:none" runat="server">
<asp:TextBox ID="txtID" runat="server" Text='<%# Eval("Empid") %>'></asp:TextBox>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

step 3:

DataTable DT = new DataTable();
DataColumn dc1 = new DataColumn("Empid");
DataColumn dc2 = new DataColumn("Empname");
DataColumn dc3 = new DataColumn("EmpSalary");
DataColumn dc4 = new DataColumn("EmpAddress");
DT.Columns.Add(dc1);
DT.Columns.Add(dc2);
DT.Columns.Add(dc3);
DT.Columns.Add(dc4);
DataRow DR;
for (int i = 0; i <>
{
DR = DT.NewRow();
DR["Empid"] = i.ToString();
DR["Empname"] = "Bala";
DR["Empid"] = "Salary";
DR["Empid"] = "Address";
DT.Rows.Add(DR);
}
grView.DataSource = DT;
grView.DataBind();

step 4:

Calling javascript for the cell through.

protected void grView_PreRender(object sender, EventArgs e)
{
foreach (GridViewRow dr in grView.Rows)
{
Label lbl = (Label)dr.FindControl("lblID");
lbl.ID = "lblID";
lbl.Attributes.Add("onclick", "javascript:lbltoTxt(this)");
TextBox txt = (TextBox)dr.FindControl("txtID");
txt.Attributes.Add("onblur", "javascript:txttoLbl(this)");
}
}

Step 5:
<script language="javascript">
function lbltoTxt(obj)
{
var divtxtObj = document.getElementById(obj.id.replace('lblID', 'txtDiv'));
var txtObj = document.getElementById(obj.id.replace('lblID', 'txtID'));
if (divtxtObj != null)
{
if (divtxtObj.style.display == "none")
{
divtxtObj.style.display = "block";
txtObj.focus();
}
}
var divlblObj = document.getElementById(obj.id.replace('lblID', 'lblDiv'));
if (divlblObj != null)
{
if (divlblObj != null)
{
divlblObj.style.display = "none"
}
}
}
function txttoLbl(obj) {
var divlblObj = document.getElementById(obj.id.replace('txtID', 'lblDiv'));
var lblObj = document.getElementById(obj.id.replace('txtID', 'lblID'));
if (divlblObj != null) {
if (divlblObj.style.display == "none") {
divlblObj.style.display = "block";
lblObj.innerText = obj.value;
}
}
var divtxtObj = document.getElementById(obj.id.replace('txtID', 'txtDiv'));
if (divtxtObj != null) {
if (divtxtObj != null) {
divtxtObj.style.display = "none"
}
}
}
</script>






Monday, August 10, 2009

javascript listbox problem

just thought of sharing this info with everyone. I am writing in my blog.

Every one no about list box control in the asp.net controls. I have tried to write javascript for selected value when enabled the multiselection for the control. In this situation am unable to get the selected value index correctly. it's coming differentyly.. post me if you know the answer..

Friday, August 7, 2009

To fire onclick event automatically on page load using Javascript

if(navigator.appName !="Microsoft Internet Explorer")
{
HTMLElement.prototype.click = function()
{
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
}

Avoid Special Character using Javascript with Regular Expression

javascript validation for special charcter.


function checkSpecial(obj,objEvent)
{
var specialChar = "^[A-Za-z0-9_]+$" //regular expression defining a 5 digit number
var objVal = obj.value;
var objVallen = obj.value.length;
if (objVal != "")
{
if (objVal.search(specialChar) == -1) //if match failed
{
if (objEvent == "keyup") {
if (objVallen > 1) {
obj.value = objVal.substring(0, parseInt(objVallen) - 1);
}
else {
obj.value = "";
}
}
else {
obj.value = "";
}
alert("Invalid character");
obj.focus();
}
}
}

Friday, July 10, 2009

attachEvent& detachEvent using Javascript

attachEvent& detachEvent

If you want to add dynamically event for the given control..have to use attach event

At the same removing have to use detach event.

Example:

<html>
<body>
<button id="myButton">Button</button>
<button onclick="function3();">Apply an event handler "Button"</button>
<button onclick="function2();">Detach</button>
<script language="JavaScript">
function function3() {
document.all.myButton.attachEvent("onclick", function1)
}
function function1() {
document.bgColor = 'red';
}
function function2() {
document.bgColor = 'white';
document.all.myButton.detachEvent('onclick', function1);
}
</script>
</body>
</html>

Wednesday, July 1, 2009

Inheritance using javascript.

After digging little inside in the prototype object. i have found can achieve inheritance. Really its nice to see the code in javascript. i will write some sample code. try to use your projects also.. In future am trying to implement javascript with the custom objects and methods. hope in future will see nice coding with javascript also.

Example

function Base()
{
this.a = "Bala";
this.b = "Bala1";
}
function Derive()
{
this.a = "Bala2";
}
function ShowAll()
{
Derive.prototype = new Base();
var show = new Derive();
alert(show.a);
alert(show.b);
}
<body onload="javascript:ShowAll()">

Output

Bala2
Bala1


Tuesday, June 30, 2009

Protype objects using Javascript

I have come across some aritcle for javascript. just thought of sharing this to everyone.so that am writing this in my blog.

let me explain my faurouite Prototype objects in the javascript. If you want to write libraries and learn advance in javascript. please try to learn prototype objects. It will be very use full.


Protytype objects.

Prototype is the keyword, Using this, we can add the custom properties and methods. Let me go through in detail.

Let me explain about custom properties in prototype objects.

function circle()
{
//
}

circle.prototype.pi="3.14";

This PI property is common for all the instances of the methods.


Custom Methods:

function ReverseBack()
{
for(i=this.length-1;i<=0;i--)
{
document.write(this.charAt(i));
}
}

String.Protype.writeBack=ReverseBack();

var message1="Bala";
var message2="alaB";

message1.writeBack();
message2.writeBack();

Output:
alaB;
Bala;





Monday, June 29, 2009

Javascript Best Practices 6

Reduce Globals

Try to avoid the global variable in the javascirpt code. Instead of that use the method objects.


var name = 'Jeffrey';
var lastName = 'Way';
function doSomething() {...}


Better way of writing the code.

var DudeNameSpace =
{
name :'Bala',
lastname:'Subramaniyam',
doSumething : function()
{
//do something
}
}

}




Drag & Drop Basics-Infragistics

Let me discuss some of the basic things about the Infragistics frame work. We have two type of drag and drop in the Infragistics.

1)Copy and paste. (Source will not delete, it will append to the destination)

2)Cut and paste. (Source will delete, it will not append to the destination)

If you want to enable the 1st one have to include the below code.

var ddb = new $IG.DragDropBehavior();

And include below code to enable the 2nd one.

var ddb = new $IG.DragDropBehavior();
var date = $get("ctl00_ContentPlaceHolder1_lblDate");
var wcgId = $get("ctl00_ContentPlaceHolder1_wcg_id");




Wednesday, June 24, 2009

Javascript Best Practices 5

Eval = Bad

Eval is the function, it will execute the string in to script code.

It will run through javascript compiler. So that it will reduce the performance of the code
Substantially.

for better code dont use Eval..






Javascript Best Practices 4

Use Always === operator, instead of ==

The issue of this operator (==) is, if the variable are different types it does not compare. It's end up with javascript error.

But in this operator( === ) variable will be converted in to objects. and it will compare.

1)!=
2) ==

Bettor Coding use below opertor instead of above.

1)!==
2)===







Tuesday, June 23, 2009

Javascript Best Practices 3

One interesting thing have faced today in the javascript. I was tried nearly two hour to enabling the focus for html tags (like table, tr, th). It does not work out.

After concluded we can give focus only for controls like textbox, button. Anchor tag..

So that I have used Anchor tag in my task.

Note:Hidden field can't give focus.




Custom ProgressBar using Javascript

Step 1:
Create below div tags in the aspx page.

<div id="modalOut" class="modalProgressOuter">
<div id="modalIn" class="modalProgressIn">
<img src="../../Themes/Theme2/ig_progressIndicator.gif" />
</div>
</div>

Step 2:

Create stylesheet with below classes.

div.modalProgressOuter
{
background-color:White;
filter:alpha(opacity=40);
opacity:0.4;
position:absolute;
display:none;
}
div.modalProgressIn
{
vertical-align:middle;
}

Step 3:

Call the below javascript through control, i mean when you click on submit button..

function showProgress() {
var objModalProgress = document.getElementById("modalOut");
var objModalIn = document.getElementById("modalIn");
if (objModalProgress != null) {
objModalIn.style.marginLeft = parseInt(document.body.offsetWidth) / 2;
objModalIn.style.marginTop = parseInt(document.body.offsetHeight) / 2;
objModalProgress.style.height = document.body.offsetHeight;
objModalProgress.style.width = document.body.offsetWidth;
objModalProgress.style.display = "block";
objModalProgress.style.left = 10;
objModalProgress.style.top = 25;
}
}





Javascript Best Practices 2

Always, Always Use Semicolons.

If you not use ;(semicolon) in the code, it's very difficult to find the error.

So please try to use everystatement with semi colon.

var someItem = 'some string'
function doSomething() {
return 'something'
}

Better

var someItem = 'some string';
function doSomething() {
return 'something';
}

Javascript Best Practices 1

Remove "Language" in the Script tag
we have used years ago, Because we unable to find that language.

Now its deprecated, so leave it out.
<script type="text/javascript" language='javascript' >
...
</script >

Monday, June 22, 2009

Drag & Drop In Infragistics New Framework

Infragistics(2009.1), In the new version drag & drop features implemented. We can implement this feature in the html element.

Note:This is very good support for DIV element in the HTML. Dont use other thin div. when you add more functionality in the page, it may give problem when you use other than DIV.

Make sure Div elment in the outermost..

Example:

<div id="tech1"><table><tbody><tr><td></td></tr></tbody></table>
</div>


Step 1:

Download original version from Infragistics 2008 or 2009

Step 2:

Download below three files from Infragistics installed folder.

1)igDragDrop.js
2)5_igObjects.js
3)igAnimation.js

Maintain same order, when you add the Above javascript in the page.

Step 3:

Add the below script in the page, which you are going to implement the drag & drop feature.This is the script will allow the drag and drop feature.

<script type="text/javascript">
if (typeof (Sys) !== 'undefined')
{
Sys.Application.notifyScriptLoaded();
Sys.Application.add_load(appLoaded);
}
</script>

Step 4:

In the below script have two method which will enable the drag & drop for html elements.Also am adding the script in the addsource element and adddrag element.

1)addSourceElement
2)addTargetElement

It will deside the from and destination of the elements.

function appLoaded() {
ddb = new $IG.DragDropBehavior();
ddb.set_defaultDropAction($IG.DragDropAction.Insert);
ddb.set_dragDropMode($IG.DragDropEffects.Move);
var list = $get("DragUnassign");
var count = list.childNodes.length;
for (var i = 0; i <>
var child = list.childNodes[i];
if (child.getAttribute)
ddb.addSourceElement(child);
}
for (var k in techIds) {
ddb.addTargetElement($get(techIds[k]), true); //Techids nothing but a div //element of the id
var jobs = $get(techIds[k]);
if (jobs != null) {
if (jobs.childNodes != null) {
var jobCount = jobs.childNodes.length;
for (var x = 0; x <>
var job = jobs.childNodes[x];
if (job.getAttribute)
ddb.addSourceElement(job);
}
}
}
}
ddb.addTargetElement($get("DragUnassign"), true);
ddb.get_events().addDropHandler(dropHandler);
var autoComplete = $find('Auto');
}

Step 5:

In this method "$IG.DragDropBehavior()" we have method called drop Handler.

This is method it will enable the events.


Note:In the present version, It cannot write a server side method for the drag & drop feature.

Step 6:


This is the method will call the webservice.

function dropHandler(sender, args)
{
var manager = args.get_manager();
if (args.get_manager()._dragging == true) {
var progressEnable = false;
var target = manager.get_targetElement().id.replace("tech", "");
techId = target;

var obtblid = techId.replace("tech", "parent");
var sourceElement = manager.get_source().element.id;
var sourceObject = manager.get_source().element.offsetParent.id;
////////////////////This is for Dragging & droping Jobs from Unassigned to Technician////////////
if ((sourceObject == "DragUnassign") && (manager.get_targetElement().id.indexOf("tech") != -1)) {
progressEnable = true;
LTDWebApp.WebClient.WebPages.Dispatcher.TechDetails.AssignJob(target, sourceElement,drcCommitdate, "ADD", onSuccessDrag, onFailureDrag);
}
//////////////////// End for Dragging Jobs from Unassigned to Technician////////////////////////
////////////////////This is for Dragging & droping Jobs from Technician to Technician////////////
else if ((sourceObject.indexOf("tech") != -1) && (manager.get_targetElement().id.indexOf("tech") != -1)) {
progressEnable = true;
LTDWebApp.WebClient.WebPages.Dispatcher.TechDetails.AssignJob(target, sourceElement,drcCommitdate, "UPDATE", onSuccessDrag, onFailureDrag);
}
////////////////////End for Dragging & droping Jobs from Technician to Technician////////////
else
{
////////////////////This is for Dragging & droping Jobs from Technician to Unassigned ////////////
progressEnable = true;
LTDWebApp.WebClient.WebPages.Dispatcher.TechDetails.UnassignJob(sourceElement);
//LTDWebApp.WebClient.WebPages.Dispatcher.TechDetails.GetUnassignedJobs(wcgId, drcCommitdate, onSuccessDragUnassign, onFailureDrag);
////////////////////End for Dragging & droping Jobs from Technician to Unassigned////////////
}
if (progressEnable == true)
{
showProgress(techId.replace("tech", "")); ////////Showing the Progress Bar
}
}
}

Step 7:

function onSuccessDrag(Result)
{
var ddb = new $IG.DragDropBehavior();
ddb.set_defaultDropAction($IG.DragDropAction.Insert);
ddb.set_dragDropMode($IG.DragDropEffects.Move);
var obtblid = "parent"+techId;
var objTbl = document.getElementById(obtblid);
var objTbody = objTbl.getElementsByTagName("tbody")[0];
objTbl.setAttribute("cellpadding", "0");
objTbl.setAttribute("cellspacing", "0");
objTbl.setAttribute("frame", "box");
objTbl.setAttribute("className", "tblAssignParenttech");
var preRows = objTbody.rows.length;
for (j = 0; j <>
{
if (j != 0)
{
objTbody.removeChild(objTbody.rows[j]);
}
}
var objRow = document.createElement("tr");
var objTd = document.createElement("td");
var objDiv = document.createElement("div");
objRow.setAttribute("className", "tblAssignParenttechRow");
objDiv.setAttribute("className", "tblscrollAssign");
objDiv.setAttribute("id", "tech"+techId);
var len = Result.length;
for (i = 0; i <>
objSplit = Result[i].split("||");
jobId = objSplit[0];
JobInterval = objSplit[1];
JobMON = objSplit[2];
var objchildjobDiv = document.createElement("div");
objchildjobDiv.setAttribute("id", jobId);
var objchildTbl = document.createElement("table");
var objchildTblBody = document.createElement("tbody");
objchildTbl.setAttribute("border", "0");
objchildTbl.setAttribute("width", "100%");
objchildTbl.setAttribute("cellpadding", "3");
objchildTbl.setAttribute("cellspacing", "1");
objchildTbl.setAttribute("className", "liBorder");
var objchildRow = document.createElement("tr");
var objchildTd = document.createElement("td");
objchildTd.setAttribute("className", "borderstyle");
var objchildTd1 = document.createElement("td");
objchildTd.innerText = JobInterval;
objchildTd1.innerText = JobMON;
objchildRow.appendChild(objchildTd);
objchildRow.setAttribute("ondblclick", "javscript:showJob(this);");
objchildRow.appendChild(objchildTd1);
objchildTblBody.appendChild(objchildRow);
objchildTbl.appendChild(objchildTblBody);
objchildjobDiv.appendChild(objchildTbl);
objDiv.appendChild(objchildjobDiv);
ddb.addSourceElement(objchildjobDiv);
}
objTd.appendChild(objDiv);
objRow.appendChild(objTd);
objTbody.appendChild(objRow);
ddb.set_defaultDropAction($IG.DragDropAction.Insert);
ddb.addTargetElement($get("DragUnassign"), true);
ddb.addTargetElement($get("tech" + techId), true);
ddb.get_events().addDropHandler(dropHandler);
hidemodalProgress();
}


Step 8:

Once the request is succeed with above method. I am generating the client side table with array data using javascript.

function onSuccessDrag(Result)
{
var ddb = new $IG.DragDropBehavior();
ddb.set_defaultDropAction($IG.DragDropAction.Insert);
ddb.set_dragDropMode($IG.DragDropEffects.Move);
var obtblid = "parent"+techId;
var objTbl = document.getElementById(obtblid);
var objTbody = objTbl.getElementsByTagName("tbody")[0];
objTbl.setAttribute("cellpadding", "0");
objTbl.setAttribute("cellspacing", "0");
objTbl.setAttribute("frame", "box");
objTbl.setAttribute("className", "tblAssignParenttech");
var preRows = objTbody.rows.length;
for (j = 0; j <>
{
if (j != 0)
{
objTbody.removeChild(objTbody.rows[j]);
}
}
var objRow = document.createElement("tr");
var objTd = document.createElement("td");
var objDiv = document.createElement("div");
objRow.setAttribute("className", "tblAssignParenttechRow");
objDiv.setAttribute("className", "tblscrollAssign");
objDiv.setAttribute("id", "tech"+techId);
var len = Result.length;
for (i = 0; i <>
objSplit = Result[i].split("||");
jobId = objSplit[0];
JobInterval = objSplit[1];
JobMON = objSplit[2];
var objchildjobDiv = document.createElement("div");
objchildjobDiv.setAttribute("id", jobId);
var objchildTbl = document.createElement("table");
var objchildTblBody = document.createElement("tbody");
objchildTbl.setAttribute("border", "0");
objchildTbl.setAttribute("width", "100%");
objchildTbl.setAttribute("cellpadding", "3");
objchildTbl.setAttribute("cellspacing", "1");
objchildTbl.setAttribute("className", "liBorder");
var objchildRow = document.createElement("tr");
var objchildTd = document.createElement("td");
objchildTd.setAttribute("className", "borderstyle");
var objchildTd1 = document.createElement("td");
objchildTd.innerText = JobInterval;
objchildTd1.innerText = JobMON;
objchildRow.appendChild(objchildTd);
objchildRow.setAttribute("ondblclick", "javscript:showJob(this);");
objchildRow.appendChild(objchildTd1);
objchildTblBody.appendChild(objchildRow);
objchildTbl.appendChild(objchildTblBody);
objchildjobDiv.appendChild(objchildTbl);
objDiv.appendChild(objchildjobDiv);
ddb.addSourceElement(objchildjobDiv);
}
objTd.appendChild(objDiv);
objRow.appendChild(objTd);
objTbody.appendChild(objRow);
ddb.set_defaultDropAction($IG.DragDropAction.Insert);
ddb.addTargetElement($get("DragUnassign"), true);
ddb.addTargetElement($get("tech" + techId), true);
ddb.get_events().addDropHandler(dropHandler);
hidemodalProgress();
}