如何从javascript访问HTML控件runat服务器

时间:2011-01-09 11:51:28

标签: javascript asp.net jquery

我有以下代码:

<telerik:GridTemplateColumn DataField="JOB_CODE" 
<EditItemTemplate> 
<input type="text" ID="JOB_CODETextBox" runat="server" 
 value='<%# Eval("JOB_CODE") %>' readonly="readonly" 
 onclick="$('#basic-modal-content').modal({
                                          appendTo:'form', persist: true,
                                          onClose: function (dialog) 
                                                   {
                                                      /*
           I want to assign here a value to the textbox control
           like this: JOB_CODETextBox = 'something...'
           I tried this: 
           $find('<%= JOB_CODETextBox.ClientID %>').value = 'something..'
           but it didn't work!! the find function returns [null]
                                                      */
                                                      $.modal.close();
                                                   }
                                         } );" />

任何帮助!!

2 个答案:

答案 0 :(得分:2)

这应该有效:

$('#'+'<%= JOB_CODETextBox.ClientID %>').val('something');

或(仅限C#):

$('<%= "#" + JOB_CODETextBox.ClientID %>').val('something');

或使用JavaScript / ECMAScript:

document.getElementById('<%= JOB_CODETextBox.ClientID %>').value = 'something';

答案 1 :(得分:0)

我不熟悉您正在使用的telerik控件,因此我将假设它与其他数据绑定控件类似。考虑到这一点,以下是使用Repeater控件的示例。

这是标记

  <asp:Repeater ID="rpt1" runat="server">
    <ItemTemplate>
      <input type="text" id="JOB_CODETextBox" runat="server" />
    </ItemTemplate>
  </asp:Repeater>

在这种情况下,我通常生成javascript服务器端。

System.Text.StringBuilder js = new StringBuilder();

js.AppendLine("  <script>");

// we'll store all the control references in a list 
// since there will be one for each item in the repeater
js.AppendLine("    var JOB_CODETextBox_list = [];"); 

for (int j = 0; j < this.rpt1.Items.Count; j++)
{
    System.Web.UI.HtmlControls.HtmlGenericControl JOB_CODETextBox;

    // try to locate the copy of the control local to each item
    JOB_CODETextBox = (HtmlGenericControl)this.rpt1.Items[j].FindControl("JOB_CODETextBox");

    if (JOB_CODETextBox != null) // make sure you found something
    {
        js.AppendFormat("JOB_CODETextBox_list.push(document.getElementById('{0}'));", JOB_CODETextBox.ClientID);
        js.AppendLine();
    }
}
js.AppendLine("  </script>");

this.Page.ClientScript.RegisterStartupScript(typeof(Page), "JOB_CODE", js.ToString(), false);

应该生成一个脚本,该脚本在Repeater中获取对该输入控件的所有实例的引用。运行后,您可以访问项目客户端,如

    JOB_CODETextBox_list[n].value = 'something';