Developing Matt

My Technical Journal

Gridview and Javascript: using dynamic fieldnames

leave a comment »

So I have this neat little accounting form I created with a gridview and I want to recalculate a couple of fields in the row based upon what they entered in the texbox.  The problem is that the textbox names for the gridivew are created on the fly and you need those names to get the values to do your calculations.  What I did was capture the textbox name and then use that name to grab the other names.  The gridview fields are named based upon the row you are on.  For example, a textbox named txtPercent on row 1 is called “GridView1_ctl01_txtPercent”  .

1.  In the onChange event of your textbox call your javascript function and pass in the textbox object you are in.

OnChange=”ChangeEvent2(this)”

2.  In you javascript function capture the number of the row you are on based upon the field you just passed in

function ChangeEvent2(fieldname){
fieldname = fieldname.id;
fieldname = fieldname.slice(13,16);
if (fieldname.charAt(2) == “_”)
{
fieldname = fieldname.slice(0,2)
}

3.  Set a new element with your created string.

var tPercent = document.getElementById(“GridView1_ctl” + fieldname + “_txtPercent”)

4.  Now you can use this element

tPercent.value = num.toFixed(1) + ‘%’;
//(rounding to 1 decimal here)

Advertisements

Written by matt

September 11, 2007 at 2:02 pm

Posted in Asp.net, javascript

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: