How to find text-box in GridView using Javascript

11,241

Solution 1

Your Gridview will be rendered as Table and your control will be contained in cell of table. You can give a try to following.

<script type=”text/javascript”>
$(document).ready(function(){
tblTable=document.getElementById(‘<<Client ID of the GridView>>’);
Cell=tblTable.rows[i].cells[j];//i and j are locations of that cell.
FirstControl = Cell.childNodes[0];
});
</script>

replace <<Client ID of the GridView>> with id of your GridView

Solution 2

The problem is your GridView creates a TextBox on each row. There is no "txt_UID" control outside of the GridView. That is what your error message is telling you.

Your JavaScript function is designed to work with one TextBox. I imagine you want the AutoComplete to work on ALL TextBox controls in the GridView.

My suggestion would be to change the JavaScript function to take a parameter with the TextBox ID and then add a CSS class to each TextBox, and finally make a wrapper JavaScript function that will enumerate the TextBox controls using getElementsByClassName, and call that wrapper function on DOM ready.

Here's what it will look like:

Add CSS class to the TextBoxes:

<asp:TemplateField ItemStyle-Width="150px" HeaderText="User Name">
    <ItemTemplate>  
        <asp:TextBox ID="txt_UID" runat="server" Text='<%# Eval("UID")%>'
            CssClass="AutoCompleteTextBox" Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>
    </ItemTemplate>
    <ItemStyle Width="150px" />
</asp:TemplateField>

New JavaScript function:

function setAutoComplete()
{
    var textBoxes = document.getElementsByClassName("AutoCompleteTextBox");
    for (var i = 0; i < textBoxes.length; i++)
    {
        addAutoComplete(textBoxes[i].id);
    }
}

Next, make your other JavaScript into a function that takes a parameter (the id):

function addAutoComplete(textBoxId) {
    $("#" + textBoxId).autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '<%=ResolveUrl("~/Service.asmx/GetUserNames") %>',
                data: "{ 'prefix': '" + request.term + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data.d, function (item) {
                        return {
                            label: item.split('-')[0],
                            val: item.split('-')[1]
                        }
                    }))
                },
                error: function (response) {
                    alert(response.responseText);
                },
                failure: function (response) {
                    alert(response.responseText);
                }
            });
        },
        select: function (e, i) {
            $("#<%=hfUserId.ClientID %>").val(i.item.val);
        },
        minLength: 1
    });
};

Finally, your on ready code changes to just call the wrapper function you created:

$(document).ready(function () { setAutoComplete(); });

Bonus: Here's a way to do it with jQuery only:

(just requires the CSS class on the TextBoxes)

$(document).ready(function () {
    $.each($(".AutoCompleteTextBox"), function (i, textBox) {
        textBox.autocomplete( /* your code */);
    })
});
Share:
11,241
moe
Author by

moe

Updated on June 29, 2022

Comments

  • moe
    moe almost 2 years

    I am trying to get access and find text-box in GridView using javascript but i am getting an error: 'The name txt_UID' does not exist in the current context'. Everything worked fine when my text-box was outside of the GridView. Here is my text-box in the gridview and my gridview is called GridView1:

     <asp:TemplateField ItemStyle-Width="150px" HeaderText="User Assigned">
        <ItemTemplate>  
         <asp:TextBox ID="txt_UID" runat="server" Text='<%# Eval("UID")%>'
            CssClass="AutoCompleteTextBox" Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>
           </ItemTemplate>
             <ItemStyle Width="150px" />
             </asp:TemplateField>
    

    Here is my JavaScript:

      <script type ="text/javascript">
            function setAutoComplete() {
                var textBoxes = document.getElementsByClassName("AutoCompleteTextBox");
                for (var i = 0; i < textBoxes.length; i++) {
                    addAutoComplete(textBoxes[i].id);
                }
            }
    </script>
    
    <script type="text/javascript">
        function addAutoComplete(textBoxId) {
            $("#" + textBoxId).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '<%=ResolveUrl("~/Service.asmx/GetUserNames") %>',
                        data: "{ 'prefix': '" + request.term + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    label: item.split('-')[0],
                                    val: item.split('-')[1]
                                }
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                select: function (e, i) {
                    $("#<%=hfUserId.ClientID %>").val(i.item.val);
                },
                minLength: 1
            });
        }; 
    

    <script type ="text/javascript">
         $(document).ready(function () { setAutoComplete(); });
        </script>
    
  • moe
    moe over 10 years
    Thanks, i am not a javascript person but how can i apply your solution to the javascript code that i posted? I need to use that code please.. thanks
  • moe
    moe over 10 years
    thanks David, do i need to change the textBoxId into txt_UID? because that is the id for my text-box thanks.
  • Dmitriy Khaykin
    Dmitriy Khaykin over 10 years
    No because the way my code works is that textBoxId is the real ID of the textBox, which the wrapper function, setAutoComplete, retrieves using the built-in JavaScript document.getElementsByClassName() method. Basically my code does not care what the ID is of your textbox - it uses the new CSS class I added to obtain a reference to all of the textboxes in the GridView (as long as you don't put that css class on any other controls or elements).
  • Dmitriy Khaykin
    Dmitriy Khaykin over 10 years
    Remember you don't have ONE textbox... you have a textbox in EACH row of the gridview. This is generated by asp.net for you as HTML elements, each one with a unique ID. The only place that "txt_UID" has any meaning is inside the GridView. There are ways to access it in .net (using FindControl method) but the way I did it is actually simpler, I think.
  • moe
    moe over 10 years
    that is right, i am making the changes now and testing it. will let you know soon. thanks
  • Dmitriy Khaykin
    Dmitriy Khaykin over 10 years
    @moe: One more thing I had a bug in my jQuery -- changed $(textBoxId) to $("#" + textBoxId), it will work now.
  • moe
    moe over 10 years
    okay let me try that because i had some issues before. thanks
  • moe
    moe over 10 years
    David, i am getting this error:Error: Object doesn't support this property or method and it is failing when setAutoComplete() function is called. I updated my initial post so please look at it see what am i doing wrong. thanks
  • Dmitriy Khaykin
    Dmitriy Khaykin over 10 years
    Are you sure the autocomplete plugin is loaded? It would seem that is the issue; calling autocomplete() before plugin is loaded would fail
  • moe
    moe over 10 years
    i was not using any autocomplete plugin before but i just downloaded and used it but still failing for the same thing
  • Dmitriy Khaykin
    Dmitriy Khaykin over 10 years
    I tested this with simple JS functions, like setting click method and then calling it and it worked; so I think the issue is with the autocomplete. Was your autocomplete script working before?
  • moe
    moe over 10 years
    yes it was working fine before without using the autocomplete plugin but the only difference is my text box was outside of the gridview
  • Dmitriy Khaykin
    Dmitriy Khaykin over 10 years
    Ok possibly you already had the autocomplete plugin. I think what is likely happening is that autocomplete (not a standard method of HTML Input element, i.e, your TextBox) is not available yet when this code is being called. Try this: comment out the $(document).ready() code, and at the very bottom of your page, add a <script> tag and just call setAutoComplete(); from it, see if that works?
  • Dmitriy Khaykin
    Dmitriy Khaykin over 10 years
    You'll need to play with it some more to sort it out. Without seeing your full code/page (or a minimized version that shows this problem) it's hard to help from here.
  • moe
    moe over 10 years
    thanks David, i tried and it did not work but i will keep playing with it
  • moe
    moe over 10 years
    Imad, i am not sure where to put this <body onload="findControl()"> </body>?? could you clarify please? thanks