How do you refresh an HTML5 datalist using JavaScript?

前端 未结 7 1059
清歌不尽
清歌不尽 2020-12-10 04:46

I\'m loading options into an HTML5 datalist element dynamically. However, the browser attempts to show the datalist before the options have loaded.

相关标签:
7条回答
  • 2020-12-10 05:29

    Quite a long time after question but I found a workaround for IE and Chrome (not tested on Opera and already OK for Firefox).

    The solution is to focus the input at the end of success (or done) function like this :

    $("#ingredient").on("keyup", function(event) {
    var _this = $(this);
    var value = _this.val();
    $.ajax({
        url: "/api/ingredients",
        data: { search: value.length > 0 ? value + "*" : "" },
        success: function(ingredients) {
            $("#ingredients").empty();
            for (var i in ingredients) {
               $("<option/>").html(ingredients[i].name).appendTo("#ingredients");
            }
            // Trigger a refresh of the rendered datalist
            // Workaround using focus()
            _this.focus();
        }
    });
    

    It works on Firefox, Chrome and IE 11+ (perhaps 10).

    0 讨论(0)
提交回复
热议问题