jQuery browser-based label/value (keyword/location) AutoComplete with submit button to window.location

StackOverflow https://stackoverflow.com/questions/22734493

  •  23-06-2023
  •  | 
  •  

Question

I have a simple label/value (keyword/location) jQuery AutoComplete that works perfectly, what I would like to do is add a submit button that will change the window.location to the value if the user happens to complete the word without clicking on the autocomplete drop down, or hits return after completing the search term. This is totally browser based solution without a backend. Any point in the right direction would be greatly appreciated! Script follows:

$(document).ready(function() {
    var data = [
        {label: 'Stack Overflow', value: 'http://stackoverflow.com'},
        {label: 'Yahoo', value: 'http://yahoo.com'},
        {label: 'Google', value: 'http://google.com'},
        {label: 'Bing', value: 'http://bing.com'}
    ];

    $("input#autocomplete").autocomplete({
        source: data,
        focus: function (event, ui) {
            $(event.target).val(ui.item.label);
            return false;
        },
        select: function (event, ui) {
            $(event.target).val(ui.item.label);
            window.location = ui.item.value;
            return false;
        }
    });
});

HTML:

<input id="autocomplete" /> <button type="submit">Go</button>

Thank you for any insight you might be able to provide!

Was it helpful?

Solution

One way to do it would be to trap both the keyup event of the input and the click event of the button (or submit event of the form, if you have one) and test for a match on your datasource:

$(document).ready(function() {
    var data = [
            {label: 'Stack Overflow', value: 'http://stackoverflow.com'},
            {label: 'Yahoo', value: 'http://yahoo.com'},
            {label: 'Google', value: 'http://google.com'},
            {label: 'Bing', value: 'http://bing.com'}
        ],
        autoNav = function (e) {
            var val = $("input#autocomplete").val().toLowerCase(),
                url = '';
            data.forEach(function (value, index, array) {
                if (value.label.toLowerCase() === val) {
                    url = value.value;
                }
            });
            if (url.length) {
                window.location.href = url;
            }
        };
    $("input#autocomplete").autocomplete({
        "source": data,
        "focus": function (event, ui) {
            $(event.target).val(ui.item.label);
            return false;
        },
        "select": function (event, ui) {
            $(event.target).val(ui.item.label);
            window.location = ui.item.value;
            return false;
        }
    }).on('keyup', autoNav);
    $('button[type="submit"]').on('click', autoNav);
});

Fiddle: http://jsfiddle.net/EpuL2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top