jQuery Autocomplete submit form on select item, button click and/or enter?

南笙酒味 提交于 2020-01-06 16:21:58

问题


I'm trying to use jQuery Autocomplete to redirect a user to a url based on the input selection. I've seen other questions that address parts of my problem, but I am having trouble putting it all together to provide the following functionality:

Trigger redirect on selection of item, as well as on enter key press and/or button click.

Jsfiddle Demo --> http://jsfiddle.net/wfaxvm43/5/

Sources:
http://jsfiddle.net/DLLVw/
jQuery autocomplete trigger button on select
JQuery Autocomplete: Submit Form on selection?

$(function () {

    var stateList = [{
        "value": "Tennessee",
            "url": "http://www.tennessee.gov"
    }, {
        "value": "Texas",
            "url": "http://www.texas.gov"
    }, {
        "value": "Colorado",
            "url": "http://www.colorado.gov"
    }, {
        "value": "Connecticut",
            "url": "http://www.ct.gov"
    }];

    $("#states").autocomplete({
        source: stateList,
        select: function (event, ui) {
            go(ui.item.url);

            // On enter key
            // if (event.keyCode == 13) {}

            // On button click
            //$(#'zip-form').submit()
        },
        response: function (event, ui) {
            if (!ui.content.length) {
                $("#no-result").show();
            } else {
                $("#no-result").hide();
            }
        }
    });
});

function go(url) {
    window.open(url);
}

回答1:


Added autoFocus: true; to focus on the first item in the results. Then had to get the url from the focused item.

focus: function (event, ui) {
        currentUrl = ui.item.url; 
}


function btnGoClick() {
if (currentUrl !== "") go(currentUrl);
}

Added .keypress mapped to 13 (enter key) on the input field for enter key redirect.

$("#states").keypress(function (event) {
if (event.which == 13) {
    event.preventDefault();
    btnGoClick();
}
});

Also set a specified url if no match was found.

http://jsfiddle.net/wfaxvm43/8/



来源:https://stackoverflow.com/questions/25449399/jquery-autocomplete-submit-form-on-select-item-button-click-and-or-enter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!