connersz
connersz

Reputation: 1223

Why can I not get the value of my textbox from inside a javascript (.js) file?

I have been making an effort to tidy my code and wanted to move some JS into some custom .JS files.

I am having an issue with getelementbyid where it cannot get the value when the script loads.

The error is 'unable to get property 'value' of undefined or null reference' I have simply moved the script into a .JS and added a link to the head of the page.

function SearchText() {

    $(".autosuggest").autocomplete({

        source: function (request, response) {

            $.ajax({

                type: "POST",

                contentType: "application/json; charset=utf-8",

                url: "/JQueryAutoComplete.aspx/GetCustomerTypeAutoCompleteData",

                data: "{'Customer':'" + document.getElementById('<%=txtCustomerType.ClientID %>').value + "'}",

                dataType: "json",

                success: function (data) {

                    response(data.d);

                },

                error: function test(xhr) {
                    alert(xhr.status + " - " + xhr.statusText);
                }


            });

Upvotes: 1

Views: 130

Answers (1)

musefan
musefan

Reputation: 48425

You cannot use ASP.Net syntax in external javascript files. So '<%=txtCustomerType.ClientID %>' will just remain AS IS, which is not a valid ID in your DOM.

I would suggest that you need to pass the ID to your SearchText function and use that to find it. For example:

function SearchText(clientID) {
    //...
    data: "{'Customer':'" + document.getElementById(clientID).value + "'}"
    //...
}

Or even better, pass the value to the function:

function SearchText(clientValue) {
    //...
    data: "{'Customer': '" + clientValue + "' }"
    //...
}

And call it from your page, something like:

SearchText(document.getElementById('<%=txtCustomerType.ClientID %>').value);

Upvotes: 2

Related Questions