Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the value of textboxt exists in Typeahead

I have this line of codes that will get all of the location in my database when user type in my textbox. The problem is I want to validate when the user change the text in my textbox and doesnt exist in my typeahead?

var path = "{{ route('search.location') }}";

$('input.typeahead').typeahead({
    source:  function (query, process) {
        return $.get(path, { query: query }, function (data) {
            return process(data);
        });
    }
}).blur(function () {
    if(source.indexOf($(this).val()) === -1) 
        alert('Not exists');
});

I've done some research using .blur function but i cant get it work?

ReferenceError: source is not defined
like image 996
Joseph Avatar asked Mar 21 '17 05:03

Joseph


1 Answers

This is an example with local data. Boolean variable something is set to true, if query at least matches one item.

$( document ).ready(function() {

var data = [
  {value: "Alabama"},
  {value: "Delaware"},
  {value: "Maine"}
];

var somethingFound = false;

$("#the-basics .typeahead").typeahead(
{
  minLength: 1,
  highlight: true 
},
{
  source: function(query, syncResults, asyncResults) {
      // use query to filter data
      var filteredData = data.filter(function(e){
        return e.value.toLowerCase().startsWith(query.toLowerCase());
      });
      console.log(filteredData.length);
      somethingFound = filteredData.length > 0;
    // return filtered data
    syncResults(filteredData);
   }
}).blur(function(){
  if (!somethingFound) {
    alert('nothing found');
  }
});
});

see also in Plunker

like image 200
Aedvald Tseh Avatar answered Oct 24 '22 04:10

Aedvald Tseh