Dynamically passing a TextBox value to JavaScript with ASP.NET

I wanted to fire a JavaScript onchange event when an ASP.NET TextBox control’s Text value changed. First, the JavaScript function, defined in the aspx page:

function loadValues(controlName) 
{
    var txtValue = document.getElementById(controlName);
    if (txtValue.value.length > 0)
 alert(txtValue.value);
}

Not very useful, but good for the demonstration.

In the Page_Load event, I assigned the loadValues function to the txtValue TextBox when the onchange event fires. Notice that I use the TextBox’s ClientID property, and I surrounded the value with single quote marks:

protected void Page_Load(object sender, EventArgs e)
{
 txtValue.Attributes.Add("onchange", "loadValues('" + txtFlickr.ClientID + "')");
}

That’s all there is to it.

Advertisements
  1. #1 by abhijit on March 13, 2012 - 11:51 am

    wasted whole day to try the above thing using hidden field. But thanx above code solved my problem.
    thanks again

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: