Monday, December 23, 2013

How to find user entered value is present in the autocomplete search list


I have created an example here to find whether user entered value is present in the autocomplete search list or not.

How I did this ?
   Jquery autocomplete has inbuilt response function, which gets called at the end of every search.
   So, just look at the response content and find if the user input value matches. Save your boolean there and
 
    finally, when you submit your form -- Just check this boolean and take your action based on that.
 
<!DOCTYPE html>
<html>
 <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <script>
  var valuePresentInSearchList = false;

  $(function() {
     // ON SUBMIT DO SOME ACTION
      $("#SUBMIT").bind("click", function() {
          alert('Entered value: '+$("#tags").val() +'     Its presence in list: ' + valuePresentInSearchList);

      });

      var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
      ];
      $( "#tags" ).autocomplete({
        source: availableTags,
          response: function( event, ui ) {
              valuePresentInSearchList = false;
              jQuery.each( ui.content, function( key, value ) {
                  for( k in value ) {
                   // alert( "key is " + [ k ] + ", value is " + value[ k ] );
                      // CHECK HERE IF INPUT VALUE IS EXACTLTY MATCH
                      // YOU CAN ALSO DO PATTERN MATCH HERE
                      if( value[ k ] ==$("#tags").val())
                      {
                      valuePresentInSearchList = true;
                      }

              }
          });
       }
      });
    });

  </script>
  <link rel="stylesheet" href="/resources/demos/style.css">
      <body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
      <button type= "submit" id= "SUBMIT" onclick="validate()" value="SUBMIT">  BUTTON</button>
</div>


</body>
</html>

You can simply copy the above code and paste it in a NEW .html file to test it.

Also I have created fiddle for the same : http://jsfiddle.net/GCnEW/

NEXT TIP  Best way of using jquery ajax

1 comment:

  1. Even if the value is in the list, it still shows false. Please reply with solution.

    ReplyDelete