JqueryUI Autocomplete prevent call on every keypre

2019-09-17 11:29发布

问题:

I am working with JqueryUI Autocomplete, what I want to do is to prevent JqueryUI autocomplete to make call on every keypress. Everything is working in perfect manner. I have bind the textfield with autocomplete but on every key press it make the call. How can i prevent call on specific keys ? e.g i want to prevent the call on arrow keys. Here is my code in Coffee.

$("#location-search").autocomplete
        source: (request, response) ->
          if request.term.length < 1
            $(".pen-dropdown").hide() 
          else
            $.ajax
              url: "http://ws.geonames.org/searchJSON?country=US&lang=en&username=awais545"
              dataType: "jsonp"
              data:
                maxRows: 10
                name_startsWith: request.term

              success: (data) ->
                rows = new Array()
                data = data.geonames
                i = 0

                while i < data.length
                  rows[i] =
                  value:        data[i].name
                  country_code: data[i].adminCode1
                  i++
                rows

                $("#location-search").parent().find(".pen-dropdown ul").html("")

                if $("#location-search").parent().find(".header-loaction").length > 0
                  $("#location-search").parent().find(".pen-dropdown ul").append("<li><a href='#'> All Area </a></li>")

                for row, i in rows
                  $("#location-search").parent().find(".pen-dropdown ul").append("<li><a href='#'> #{row['value']}, #{row['country_code']} </a></li>")
                  window.dropdownli = $(".pen-dropdown li")
                  window.dropdownliSelected = undefined

                for li in $("#location-search").parent().find(".pen-dropdown ul li")
                  $(li).click(setLocationTitle)

                $("#location-search").parent().find(".pen-dropdown").show()

Thanks

回答1:

I had similar issue. I fixed it using event "search( event, ui )" in autocomplete.

 $("#autocompleteText").autocomplete({
            search: function (event, ui) {
           /*keyCode will "undefined" if user presses any function keys*/
                if(event.keyCode)
                { event.preventDefault(); }
            },
            autoFocus:false,
            minLength:3,
            source: function (request, response) {
                //make remote call for result.                   
            }

        });