3

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>

3 Answers 3

1

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 */);
    })
});
Sign up to request clarification or add additional context in comments.

14 Comments

thanks David, do i need to change the textBoxId into txt_UID? because that is the id for my text-box thanks.
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).
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.
that is right, i am making the changes now and testing it. will let you know soon. thanks
@moe: One more thing I had a bug in my jQuery -- changed $(textBoxId) to $("#" + textBoxId), it will work now.
|
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

2 Comments

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
Imad, i am not sure where to put this <body onload="findControl()"> </body>?? could you clarify please? thanks
0

you can use name attribute and the grid id to find it:

<asp:TextBox ID="txt_UID" name="mytextbox" runat="server" Text='<%# Eval("UID")%>'
        Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>

the javascript part:

$("#<%=MyGrid.ClientID %>[name=mytextbox]").autocomplete({});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.