How to get the id of a textbox that is using jQuery UI AutoComplete

Recently I had a need for getting the id value of a textbox that was using the jQuery UI AutoComplete plugin. I wanted to pass this id value as a parameter and use it in my Ajax call to my database. To add some extra complexity, my project was using the AutoComplete plugin on numerous textboxes. I didn't want to make a function for each textbox that would be using the AutoComplete so I had to set it up in a slightly generic way.

The trick to getting this working is to wrap your AutoComplete function call around an 'each' loop for the textboxes so that the 'attr' function becomes available to use and allows us to grab the id value we need to use in our Ajax call.

Below is the code I used. As you can see I do a 'each' call for every textbox that uses the 'tb' css class. If you've used the AutoComplete plugin before the rest of this code should be familiar to what you're using. If not, I'd recommend taking a look at the plugin documentation.

$("input:text.tb").each(function () {
        var thisElement = $(this);
        $(this).autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "FetchLocationList/TestPage",
                    data: "{ 'loc': '" + request.term + "', 'textboxid': '" + thisElement.attr("id") + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                value: item.Name,
                                key: item.Code
                            }
                        }))
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            },
            minLength: 3
        });
    });


Share this post


blog comments powered by Disqus

Updates

Follow me online at TwitterFacebook or Flickr. If you want to get in touch with me try emailing me.

Latest Tweets