Skip to content Skip to sidebar Skip to footer

How To Implement Jquery Ui Autocomplete 'autofill' And/or 'selectfirst' Features?

First, Let me start by saying thatI am aware of other similar questions, like this one here: How to implement 'mustMatch' and 'selectFirst' in jQuery UI Autocomplete? but it doesn

Solution 1:

I was going to post a bounty but finally figured it out.

Here is the solution I came up with. After playing around with this, I figured out that the plugin uses .data() to store the option item data. So I was able to get the full object and parse out the data that I needed to fulfill other elements. Then the challenge was to recognize when a selection was valid even if the user didnt click or select an option. For that I check to see if any options match the value, if they do I replicate the select. Otherwise I clear the fields. Then I leveraged the .data() again to store whether the choice was valid or not, and if it was not I was able to clear the fields again. Below is my code.

Comments are welcome.

$('#autocomplete_input').autocomplete({
        source: function (request, response) {
            $.get("/DataHandler.ashx", { Type: "ExpectedType", Query: request.term }, function (result) {
                var sourceData = $.parseJSON(result);
                response($.map(sourceData, function (item) {
                    return { label: item.PortName, value: item.PortName, source: item };
                }))
            });
        },
        minLength: 3,
        change: function (event, ui) {
            if (ui.item) {
                $('#another_element"]').val(ui.item.source.PortId);
            }
            else {
                if (!$(this).data('valid')) {
                    $(this).val('');
                    $('#another_element').val('');                    
                }
            }
            $(this).data('valid', false);
        }
    }).live('blur', function (e) {
        if ($('.ui-autocomplete li:visible').length > 0) {
            item = $($(".ui-autocomplete li:visible:first").data()).attr('item.autocomplete');
            $(this).val(item.label);
            $('#another_element').val(item.source.PortId);
            $(this).data('valid', true);
        }
    });

Post a Comment for "How To Implement Jquery Ui Autocomplete 'autofill' And/or 'selectfirst' Features?"