Tuesday, June 16, 2009

Need for having Eval function in javascript



Javascript has function called
eval() which evaluates a string and executes it as if it was script code.

Let us see the need for having this eval function.

Consider the below sample code in javascript.


document.myform.category_name1.value=””;
document.myform.category_name2.value=””;
document.myform.category_name3.value=””;
category_name1,category_name2,category_name3.....which are dynamic in a page.
suppose we want to achieve above three statements in a for loop

for(i=1;i<=3;i++)
{
var category_name=“category_name”+i;
document.myform.category_name.value=””;
}
Trying above way, does not work.

Trying following way, will work well.
for(i=1;i<=3;i++)
{
category_name=”category_name”+i;
temp="myform."+category_name;
clear=temp+'.value="";' ;
eval(clear);
}


We can refer this article to know more about eval.

More Articles...

No comments:



Thanks for visiting our blog


twitterrss facebook linkedin YouTube subscribe


Subscribe via email

Enter your email address: