A Coder
A Coder

Reputation: 3046

Get hidden field value in jQuery inside a Gridview

I need to get the value of the hidden field which is inside the gridview using jQuery.I have tried but it doesn't work for me.

//Code:

 <script type="text/javascript">
        $(document).ready(function () {
            $("table[id*='<%=grdTest.ClientID %>]' a[id*=getID]").click(function () {
                alert($(this).closest("tr").find("input[type=hidden][id*=key]").val());
            });
        });
    </script>

 <asp:GridView ID="grdTest" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:HiddenField ID="key" runat="server" Value='<%#Eval("ID") %>'> </asp:HiddenField>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Select">
                <ItemTemplate>
                    <a href="#" id="getID">Click</a>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

When i click the link i should get the value. Now there is no response. Where am i wrong?

Upvotes: 0

Views: 4364

Answers (2)

AdamT
AdamT

Reputation: 71

I came across this exact same problem recently and this is how I managed to overcome it. I was led to believe you can't add a class to a hidden field as there is no need for it since it is hidden, so instead you wrap a <span class="hiddenfield"></span> around the hidden field within the gridview. You can then target the class of the span followed by the input in jquery. So your code will look as follows:

<asp:TemplateField>
                    <ItemTemplate>
    <span class="hiddenfield">
                        <asp:HiddenField ID="key" runat="server" Value='<%#Eval("ID") %>'> </asp:HiddenField>
    </span>
                    </ItemTemplate>
                </asp:TemplateField>
    alert($(this).closest("tr").find(".hiddenfield input").val());

This is my first answer so I hope this helps, that is if it isn't already sorted.

Upvotes: 2

Bibhu
Bibhu

Reputation: 4081

Instead of searching using ID, you can assign a class to the hidden field, and use it as the selector. The ID will not work as the render time a different auto generate ID will be assigned to the hidden field, like this :

<input type="hidden" value="0" id="clt100_clt100_29042034982304_key" />

Upvotes: 0

Related Questions