Monday, August 15, 2011

jQuery tips & tricks

jQuery tips and tricks:-

I am new in jquery but there are several things i learnt during implementation of jQuery into projects (asp.net MVC).

1. Disable vs Readonly:-
we can not send Disable controls value to server so for this purpose, we have readonly property and as it is the part of jQuery so it is control independent property.
$("#txtName").attr("readonly","readonly");
$("#txtName").removeAttr("readonly");

2. each vs chaining

we have 2 option to associate a particular action to set of controls returned by selector
a) use Intrator method to assign action to each value or
$(".txtbxClass").each(function(index){ $(this).click(function (){ this.value+="txtbxClass";}););

b) we can use chaining and assign all actions in a single statement.
$(".txtbxClass").click(function (){ this.value+="txtbxClass";});
Both statement will work in similar way!!!!!!!!!!
but the second option is more clean code and easy to understand.

3.

Function in Java script

Function in javascript:

DataType : Function is a datatype in javascript as other datatype like var,string and date.
e.g:
function checktype()
{}
alert(typeof(checktype));

As mentioned above function is datatype so we can assign function to variable, pass function as parameter to a function and can return as value.

Ex1:-
var funVal= function add(n1,n2)
{
return n1+n2;
}

funVal(8,19);

Ex2:-

function addValues(n1,n2)
{
return function(){
return n1+n2;
}
}

var retFnc= addValues(8,9);
retFnc();

Ex3:-

function addvalues(fns,fnr,n1,n2)
{
fns();
print(n1+n2);
fnr();
}
function fns(){
print("Execution start:");
}
function fnr()
{
print ("Execution end:");
}

addValues(fns,fnr,23,89);

Because function is datatype there are some methods associated with it:
1. call
2. apply

1) call takes 1or more than one parameter as calling parameters

function addValues(n1,n2)
{
return n1,n2;
}

addValues.call(null,5,6);

2) apply is different for call as if there is no of parameter is not fixed better approach is to use apply method.

function addValues()
{

for(var i=0;i
{
print(arguments[i].toString());
}

}

addValues.apply(null,[4,6,7]);
addValues.apply(null, [34,31,23,45]);

One more thing is associated with function that i would like to talk is context we are also able to use context inside javascript function.

Ex:-
var thisContext= { val=0;}


function addValue(n1)
{
return this.val+n1;
}

print(addValue.call(thisContext,n1));

is the way use controls in jQuery.

Ex:
$("#btnOk").click(function {
this.Value+="Clicked!!!!";
});

Happy Programming :)
Let knowledge flow like water!!!!!!!!!!!!!