views:

77

answers:

4

i have a button with id Button1 on page load function i m trying to call javascript function like this

int l = files.Length;
Button1.Attributes.Add("onclick", " alertMe(l);");

where files.length is some integer value,now i m trying to pass this value in alertMe function can anyone tell me is it a write way to pass the value if yes how can i retrieve it in alertMe function

+2  A: 
int l = files.Length;
Button1.Attributes.Add("onclick", " alertMe(" + l + ");");
David Hedlund
thnx but how can i retrieve it in the alertMe function
sumit
Fabian Vilers' response will help you with that part
David Hedlund
Still, I think it would be better to use the `Button.OnClientClick` property. See my answer for an example.
Jørn Schou-Rode
That's definitely a valid point, i upvoted you for that. I just wanted to show with the least amount of modification, what sumit was doing wrong.
David Hedlund
A: 

try:

int l = files.Length;
Button1.Attributes.Add("onclick", " alertMe(" + l.ToString() + ");");
JustLoren
+1  A: 
function alertMe(length)
{
    alert("you passed a length of: " + length);
}
Fabian Vilers
+1 for the part of sumit's question that i missed
David Hedlund
+1  A: 

In your sample, the value passed to the javascript function is always 1. Also, you might want to use the Button.OnClientClick property instead, as this ensures that ASP.NET's own button handling code is left intact. Your C# code should probably look something like this:

int fileCount = files.Length;
Button1.OnClientClick = "alertMe(" + fileCount + ");"

In the javascript, make sure you declare the formal parameter in the function signature:

function alertMe(fileCount)
{
    alert(fileCount);
}
Jørn Schou-Rode