Shah
Shah

Reputation: 1654

how to access dynamically generated textboxes and apply some validation

I am generating dynamically textboxes and adding them to a placeholder as below.

 TextBox txt = new TextBox();

 txt.ID = "txt" + ds.Tables[0].Rows[i]["id"].ToString();
 txt.Width = 250;
 txt.ToolTip = ds.Tables[0].Rows[i]["TotalMarks"].ToString();
 phMemberTextboxes.Controls.Add(txt);
 phMemberTextboxes.Controls.Add(new LiteralControl("\n<br />"));

i want to access the values from these textboxes. and need to check if the textbox value is less than tooltip value. If so need to reset textboxes. How can i do so?

Upvotes: 0

Views: 528

Answers (2)

Software Engineer
Software Engineer

Reputation: 3956

When u add dynamically generated controls to placeholder, their IDs get changed, you have to set control's ClientID first to access it at client side:

txt.ClientID = "txt" + ds.Tables[0].Rows[i]["id"].ToString();
txt.Attributes.Add("onblur", string.Format("validateControl('{0}');", txt.ClientID);

Then in your javascript:

function validateControl(ctrlId){
    var txtCtrl = document.getElementById(ctrlId);
    int txtVal = txtCtrl.value;
    // Note that getAttribute doesn't work in IE 6 and requires exact property name
    var txtMarks = parseInt(txtCtrl.getAttribute("title")); 
    if (txtVal.length < txtMarks.length){
        // Reset textbox value and show the message
        txtCtrl.value = "";
        var msg = "Value must be greater than " + txtMarks;
        alert(msg);
        txtCtrl.focus();
    }
}

Upvotes: 1

Pankaj
Pankaj

Reputation: 10095

Set TextBox onclick Attributes.

YourButton.Attributes.Add("onclick", "YourJavascriptFunction('" + txt.ClientID + "');");

Now in YourJavascriptFunction

function YourJavascriptFunction(ID)
{
    var txtCtrl = document.getElementById(ctrlId);
    int txtVal = txtCtrl.value;
    // Note that getAttribute doesn't work in IE 6 and requires exact property name
    var txtMarks = parseInt(txtCtrl.getAttribute("title")); 
    if (txtVal.length < txtMarks.length){
       // Reset textbox value and show the message
       txtCtrl.value = "";
       var msg = "Value must be greater than " + txtMarks;
       alert(msg);
       txtCtrl.focus();
    }

}

Upvotes: 0

Related Questions