Friday, June 23, 2017

Check if the value of textboxt exists in Typeahead

Leave a Comment

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 

1 Answers

Answers 1

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

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment