user3260999
user3260999

Reputation: 21

JQuery ui autocomplete trigger function after programatically search

I have a street input field with JQuery ui autocomplete suggestions. After the user selected one of the suggestions, he should enter the number. Then on number blur a function validates with below autocomplete search function if the street is in the suggestions. If yes, an other function should be called. I can't call the other function.

Here is my code:

$("#street").autocomplete({ 
   source: "street.php",
minLength: 2,    
    search: function (event,ui) {
            //Return to input field
            if (ui.item==null)
             {
             alert("Please select a street.");          
           $("#street").focus();
           return;
            } else{
                //call an outside function,
                //does not work
                address-search();
            }               
    }
  });

Thank you in advance for help for solving this problem.

Upvotes: 1

Views: 1159

Answers (2)

user3260999
user3260999

Reputation: 21

thank you, I found a solution for my own. https://jsfiddle.net/dupxj3mu/5/

function search_street() {
    $("#street").on("autocompletechange", function(event, ui) {
      if (ui.item === null) {
        $("#hiddenstreet").val($("#street").val());
        $("#street").val("");
        return false;
      }
    });
    if ($("#street").val() === "") {
      $("#street").val($("#hiddenstreet").val());    
      $("#street").focus();
      alert("Please select a street.");     
      $("#hiddenstreet").val("");
      return false;
    } else {
      address_search();
    }
  }

But the autocomplete test only run once then again address_search() will be called by wrong street names, too. I will empty the street input field on wrong input and put aside in a DIV that the street input was wrong. Then address_search() will run only on right selection.

Upvotes: 0

tymothytym
tymothytym

Reputation: 1611

I think you need the search callback to do that:

$("#street").on("autocompletesearch", function(event, ui) {
    if (ui.item === null) {
       alert("Please select a street.");          
       $("#street").focus();
    } else {
       address-search();
    }
});

Documentation here: http://api.jqueryui.com/autocomplete/#event-change

Edit: Based on your specific code, I think you want this:

$(document).ready(function() {
  var availableTags = [
    "1.Street",
    "2.Street",
    "3.Street"
  ];
  $("#street")
    .autocomplete({
      source: availableTags,
      minLength: 2,
    })
    .on("autocompletechange", function(event, ui) {
      if (ui.item === null) {
        alert("Please select a street.");
        $("#street").focus();
        xhr.abort();
      } else {
        address_search();
      }
    });
  function address_search() {
    alert($("#street").val());
  }
});

Updated jsfiddle: https://jsfiddle.net/dupxj3mu/3/

Upvotes: 1

Related Questions