简体   繁体   中英

Get list options from jQuery UI autocomplete with url

My element is a jQuery autocomplete element that gets its options from a URL:

$element.autocomplete({
    source: '/mysearchurl',
    open: function () {
        //...
    },
    response: function (event, ui) {
        //...
    },
    select: function (event, ui) {
        //...
    }
});

It works as expected: The user enters some characters, and it displays the matching values in a drop-down.

What I want now, in my Javascript, is to get the options out of the list, ideally as the same JSON that it gets from the URL. I could try to collect them from the element through something like this:

$($element.data('ui-autocomplete').menu.element[0].list.childNodes).each()

But maybe there's a better way?

I propose to use source function with an Ajax call inside:

 $("#autocomplete").autocomplete({ source: function(request, response) { var el = this.element; var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i"); $.ajax({ url: "https://api.myjson.com/bins/qnhcd", type: "GET", contentType: "application/json", dataType: "json", success: function(data, textStatus, jqXHR) { var selection = data.filter(function(item) { if (matcher.test(item.value)) return item.value; }); el.data("source", selection); response(selection); } }); } }); $( "#autocomplete" ).on( "autocompleteresponse", function( event, ui ) { refreshList(); }); refreshList = function() { var source = $("#autocomplete").data("source"); console.log("refreshList", source); $("#list").empty(); if (source) { for (var i in source) { $("#list").append("<li>" + source[i].value + "</li>") } } else { $("#list").append("<li>No options</li>") } }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" /> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <label for="autocomplete">Select a programming language: </label> <input id="autocomplete"> <br> <button onclick="refreshList()"> refresh list </button> <br> <ol id="list"> </ol>

here is a jsfiddle: http://jsfiddle.net/beaver71/svLsw13f/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM