开发者

jQuery Autocomplete "no result" not clickable or selectable

开发者 https://www.devze.com 2022-12-17 10:40 出处:网络
How to properly handle \"no result\" case in jQuery Autocomplete function that the \"no result\" is not clickable or selectable?

How to properly handle "no result" case in jQuery Autocomplete function that the "no result" is not clickable or selectable?

In the "parse" part I add "no result" item:

 p开发者_JAVA技巧arse: function(data) {
     var array = new Array();
     if (!data || data.length == 0) {
         array [0] = { data: { Title: "No results" }, value: "No results", result: "No results"};
     }
 }

So when are there no results, it shows only "No results". But it is selectable and clickable which is not OK, because this value is then passed to the text input.

EDIT

Complete javascript part:

<script type="text/javascript">
                var NoResult= "No result";
                $(function() {
                    $("#txtTextAnimal").autocomplete('<%= Url.Action("Find", "Animal") %>', {
                        dataType: 'json',
                        delay: 100,
                        parse: function(data) {
                            var rows = new Array();
                            for (var i = 0; i < data.length; i++) {
                                rows[i] = { data: data[i], value: data[i].Title, result: data[i].Title };
                            }
                            if (rows.length == 0) {
                                rows[0] = { data: { Title: NoResult}, value: "", result: NoResult};
                            }
                            return rows;
                        },
                        formatItem: function(item) {
                            return item.Title;
                        }
                    }).result(function(event, item) {
                        if (item.Title != NoResult) {
                            $("#hidAnimalId").val(item.Id);
                            $("#hidAnimalId").closest("form").submit();
                        }

                    });
                });

            </script>


Im not sure which autocomplete plugin you are using, but there must be a "click" handler somewhere? In this function you could just check the for "No Results".

Alternatively, could you just set the array value to nothing when there is no data? So...

var array = new Array();
if (!data || data.length == 0) {
  array [0] = { data: { Title: "No results" }, value: "", result: "No results"};
}

Updated here: You can use the result option...This is untested, so some tinkering will probably be needed

jQuery('#yourTextbox').result(function(event, data, formatted) {
  if (!data || formatted == 'No Result'){
    return false;
  } else {
    // return true or some other logic?
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消