anesthetic anesthetic - 4 months ago 18
Javascript Question

Accessing ASP textbox inside gridview for JS script

I have an asp:Gridview and I would like my JS script to trigger a modal when a cell is focused.
I have the following in my aspx file:

<asp:GridView ID="gridviewSLds" runat="server" CellPadding="0" ForeColor="#333333" GridLines="Both" AutoGenerateColumns="False" OnRowCreated="gridviewSLds_RowCreated">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
<asp:TemplateField ItemStyle-BorderWidth="0">
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("Id") %>' />
<asp:BoundField DataField="item" HeaderText="Metric" SortExpression="item" ReadOnly="false" />
<asp:TemplateField HeaderText="Item">
<asp:TextBox onfocusin="select()" runat="server" Text='<%# Bind("item") %>'
ID="txtfocus" AutoPostBack="true"></asp:TextBox>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />


My script is as follows:

var usrfocustxt = document.getElementById('<%txtfocus.item%>');

itemtypetxt.onfocus = function () { = "block";

But it tells me the name 'txtfocus' does not exist in the current context. What am I doing wrong?


You are doing several things wrong. First of all if you want an ID in javascript you should use it like this:

var usrfocustxt = document.getElementById('<%= txtfocus.ClientID %>');

But this will still give you the error 'txtfocus' does not exist in the current context.

Because a GridView (and other Controls that repeat data), will give the TextBox a unique name and ID so it does not occur multiple times on a page. If you look at the HTML source you could have seen that the TextBox HTML code now looks something like this:

<input name="ctl00$mainContentPane$rptr$ctl05$txtfocus" id="mainContentPane_rptr_txtfocus_5" type="text">

The name and ID have been modified with a index number and other data to make it unique. So to find the correct TextBox it's much easier to call the modal popup function like this.

<asp:TextBox ID="txtfocus" runat="server" onfocus="focusTextBox(" class="modalpopup"></asp:TextBox>

Or you can bind the function to the TextBox with jQuery and a class name.

<script type="text/javascript">
    $(document).ready(function () {
        $('.modalpopup').focus(function () {