Sunday, May 31, 2015

jQuery autocomplete in PHP and force to pickup



jQuery autocomplete introduction
 https://jqueryui.com/autocomplete/ 

 My example: autocomplete data from php
Input box values force to come from autocomplete dropdown

Two files:  jquery_autocomplete.php, tags.php
jquery_autocomplete.php
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  $(function() {

    $( "#tags" ).autocomplete({
      source: 'tags.php',
      minLength : 0,

      select : function(event, ui) {
             newname = ui.item.label; 
             var url = '';
             $.post(url, ui.item.label, function(data) {
                    //alert(ui.item.label);
               
                });   
            },
      change : function() {    
            curname = $("#tags").val();
            if(curname.trim()!= newname) {
              alert("You need to pick a tag from the tag list.");
              $("#tags").val(oldname);
            }

       }
    }).focus(function(){
        $(this).autocomplete('search');
        oldname=$(this).val();
    });
   
  });
     
  </script>
</head>
<body>
 <form onsubmit="return false" id="editContractInfo">
<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input type="text" id="tags" name="tags">
</div>
</form>

</body>
</html>


 tags.php
<?php
$availableTags = array(
     array("label"=>".Tbd", "value"=>".Tbd"),
     array("label"=>"ActionScript", "value"=>"ActionScript"),
     array("label"=>"AppleScript", "value"=>"AppleScript"),
     array("label"=>"Asp", "value"=>"Asp")    
    );
echo json_encode($availableTags);
?>

Video: jQuery autocomplete in PHP and force to pickup

No comments:

Post a Comment