2011-11-16 191 views
1

我有一個帶有文本輸入和選擇框的窗體。文本字段使用自動提示來允許用戶從列表中選擇選項。從自動提示中選擇一個值後,選擇選項框會根據選擇填充選項。如何使第二個自動完成選項依賴於使用jQuery的第一次自動完成選擇?

我正在努力改變代碼,以便第二個盒子也是文本輸入,以免限制用戶的選擇(即,如果用戶不想從中選擇,這兩個字段都應該允許自由文本輸入可用的選擇)。

我想我已經盯着這段代碼太久了,並會喜歡一些幫助。很顯然,這些變化需要進入loadCountry,populateSelectloadcountrySelect函數。

我使用PHP,jQuery和jQuery UI Autocomplete

任何幫助你可以提供將非常感激!

腳本:

<script src="../../scripts/jquery-1.6.4.js"></script> 
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script> 
<script src="../../scripts/jquery.ui.widget.js"></script> 
<script src="../../scripts/jquery.ui.position.js"></script> 
<script src="../../scripts/jquery.ui.autocomplete.js"></script> 
<script type="text/javascript"> 

$(document).ready(function() { 

    function ord(chr) { 

     return chr.charCodeAt(0); 

    } 

    function chr(num) { 

     return String.fromCharCode(num); 

    } 

    function quote(str) { 

     return '"' + escape(str.replace('"', "'")) + '"'; 

    } 

    String.prototype.titleCase = function() { 

     var chars = [" ", "-"]; 
     var ths = String(this).toLowerCase(); 

     for (j in chars){ 

      var car = chars[j]; 
      var str = ""; 
      var words = ths.split(car); 
      for(i in words){ 

       str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1); 

      } 

      ths = str.substr(1); 

     } 

     return ths; 

    } 

    function incrementTerm(term) { 

     for (var i = term.length - 1; i >= 0; i--){ 

      var code = term.charCodeAt(i); 

      if (code < ord('Z')) 

       return term.substring(0, i) + chr(code + 1); 

     } 

     return '{}' 

    } 

    function parseLineSeperated(data){ 

     data = data.split("\n"); 

     data.pop(); // Trim blank element after ending newline 

     var out = [] 

     for (i in data){ 

      out.push(data[i].titleCase()); 

     } 

     return out; 

    } 

    function guess(value){ 

     var oldValue = $('.continent_autocomplete').val(); 

     if (oldValue == value) 

      return; 

     $('.continent_autocomplete').val(value); 

     $('.continent_autocomplete').caret(oldValue.length, value.length); 

    } 

    function clearGuess(){ 

     var field = $('.continent_autocomplete'); 

     field.val(field.val().substring(0, field.caret().start)); 

    } 

    function loadcontinent(request, response) { 

     var startTerm = request.term.toUpperCase(); 

     var endTerm = incrementTerm(startTerm); 

     $.ajax({ 

      url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm, 

      success: function(data) { 

       var items = parseLineSeperated(data); 

       response(items); 

      }, 

      error: function(req, str, exc) { 

       alert(str); 

      } 

      }); 

    } 

    function loadcountry(handler) { 

     var continent = $('.continent_autocomplete').val().toUpperCase(); 


     $.ajax({ 

      url: '/db/country.php?key=' + continent, 

      success: function(data) { 

       handler(parseLineSeperated(data)); 

      }, 

      error: function(req, str, exc) { 

       alert(str); 

      } 

      }); 

    } 

    function populateSelect(select, options) { 

     select.html(''); 

     if (options.length) { 

      enableSelect(); 

      for (i in options){ 

       var option = options[i]; 

       select.append($('<option></option>').val(option).html(option)); 

      } 

     } else { 

      disableSelect('Country'); 

     } 

    } 

    function loadcountrySelect(continentObj){ 

     disableSelect('Loading...'); 

     loadcountry(function(options){ 

      populateSelect($('.country_autocomplete'), options); 

     }); 

    } 

    function disableSelect(message){ 

     var select = $('.country_autocomplete'); 

     select.html("<option>" + message + "</option>"); 

     select.attr('disabled', true); 

    } 

    function enableSelect(){ 

     var select = $('.country_autocomplete'); 

     select.attr('disabled', false); 

    } 

    populateSelect($(".country_autocomplete"), []); 

    $("input.continent_autocomplete").autocomplete({ 

     source: loadcontinent, 

     select: function(event, ui){ 

      $("input.continent_autocomplete").val(ui.item.value); 

      loadcountrySelect(event.target); 

     } 

    }); 


    $("input.continent_autocomplete").keyup(function (event){ 

     var code = (event.keyCode ? event.keyCode : event.which); 

     if (code == 8) { // Backspace 

      clearGuess(); 

     } 

     event.target.value = event.target.value.titleCase(); 

     loadcountrySelect(event.target); 

    }); 
}); 

</script> 

HTML:

<div id="continent_name"> 
    <label> Continent Name:</label> 
    <input type="text" id="continent_name" name="continent_name" class="continent_autocomplete" /> 
</div> 
<div id="country"> 
    <label> Country:</label> 
    <input type="text" id="country_autocomplete" name="country_autocomplete" class="country_autocomplete" /> 
</div> 

continent.php

<?php 

$db_host  = 'XXX'; 
$db_user  = 'XXX'; 
$db_password = 'XXX'; 
$db_name  = 'XXX'; 

$db = new mysqli($db_host , $db_user ,$db_password, $db_name); 

if(!$db) { 

    echo 'There was a problem connecting to the database'; 
} else { 

    if(isset($_GET['startkey'])) { 
     $mysearchString = $db->real_escape_string($_GET['startkey']); 


     if(strlen($mysearchString) >0) { 


      $query = $db->query("SELECT DISTINCTROW Continent 
           FROM locations 
           WHERE Continent 
           LIKE '$mysearchString%' 
           LIMIT 10"); 

      if($query) { 

       while ($result = $query ->fetch_object()) { 

         print ucwords(strtolower($result->Continent))."\n"; 
       } 

      } else { 

       echo 'ERROR: There was a problem with the query.'; 
      } 

     } else { 

     } 

    } else { 

     echo 'Access denied.'; 
    } 
} 
?> 

country.php

<?php 
$db_host  = 'XXX'; 
$db_user  = 'XXX'; 
$db_password = 'XXX'; 
$db_name  = 'XXX'; 

$db = new mysqli($db_host , $db_user ,$db_password, $db_name); 

if(!$db) { 

    echo 'There was a problem connecting to the database'; 

} else { 

    if(isset($_GET['key'])) { 

     $mysearchString = $db->real_escape_string($_GET['key']); 

     if(strlen($mysearchString) >0) { 

      $query = $db->query("SELECT Continent,Country,Abbrev 
           FROM locations 
           WHERE Continent 
           LIKE '$mysearchString%' 
           ORDER BY Country 
           LIMIT 20");  

      if($query) { 

       while ($result = $query ->fetch_object()) { 

        print ucwords(strtolower($result->Country))."/". 
          ucwords(strtolower(strtok($result->Abbrev,";")))."\n"; 

       } 

      } else { 

       echo 'ERROR: There was a problem with the query.'; 

      } 

     } else { 

     } 

    } else { 

     echo 'Access denied.'; 

    } 

} 
?> 
+0

'country.php'是否有一個參數來過濾搜索?如果是這樣,那是什麼? –

+0

@AndrewWhitaker剛剛爲上面的continent.php和country.php添加了代碼。 – Michael

回答

0

您將需要修改您的PHP以使其最佳運行(在服務器上進行過濾)。

;

$continent = $db->real_escape_string($_GET['continent']); 
$country = $db->real_escape_string($_GET['country']); 

$query = $db->query("SELECT Continent,Country,Abbrev 
    FROM locations 
    WHERE Continent ='$continent' and Country like '$country%' 
    ORDER BY Country 
    LIMIT 20"); 

(我不知道PHP,請帶一粒鹽):所以,它有兩個參數(一個國家,一個大陸)查詢你的數據庫我會更新你的PHP

基本上,通過一個大陸(在第一個input中選中)以及國家搜索字符串(在第二個輸入中鍵入)。

接下來,您將需要將自動填充小部件應用到第二個input。喜歡的東西:

$("#country_autocomplete").autocomplete({ 
    source: function (request, response) { 
     var continent = $("#continent_autocomplete").val() 
      , country = request.term; 

     $.ajax({ 
      url: '/db/country.php?continent=' + continent + "&country=" + country, 
      success: function(data) { 
       response(parseLineSeperated(data)); 
      }, 
      error: function(req, str, exc) { 
       alert(str); 
      } 
     }); 
    } 
}); 

只是對一些潤色,你可能會想清除#country_autocomplete#continent_autocomplete變化。你可以做到這一點通過增加對自動完成的change事件的事件處理程序:

$("input.continent_autocomplete").autocomplete({ 
    source: loadcontinent, 
    change: function() { 
     $("#country_autocomplete).val(''); 
    } 
}); 

最後,你要刪除與填充全國select做任何代碼,因爲你不再需要它。

0

的jQuery插件Autocomplete like Google支持這樣的功能:

自動完成功能。PHP(AGLY風格,在一個地方的整個邏輯 - 只是爲了顯示原理)

if(!empty($_GET['foo_name']) && !empty($_GET['bar_number'])) { 
    $sql = 'SELECT ... FROM ... WHERE'; 
    $db = new MySQLi(...); 
    $db->query($sql); 
    $numbers = []; 
    while($row = $result->fetch_assoc()){ 
     $numbers[] = $row['bar_number']; 
    } 
} 
echo json_encode($numbers); 

autocomplete.html

<link href="/components/autocompletelikegoogle/jquery.autocomplete.css" media="screen" rel="stylesheet" type="text/css"> 
<script type="text/javascript" src="/components/autocompletelikegoogle/jquery.autocomplete.js"></script> 
<script type="text/javascript" src="/js/autocomplete.js"></script> 

<input type="text" name="foo_name" id="foo-name" value=""> 
<input type="text" name="bar_number" id="bar-number" value=""> 

autocomplete.js

$(function() { 
    $("#foo").autocomplete({ 
     minLength: 3, 
     limit: 5, 
     source : [{ 
      url:"/my/ajax/controller/foo?data[foo_name]=%QUERY%", 
      type:'remote' 
     }], 
    }); 
}); 

$(function() { 
    $("#bar").autocomplete({ 
     minLength: 3, 
     limit: 5, 
     appendMethod:'replace', 
     source : [ 
      function(query, add) { 
       fooName = $('#foo-name').val(); 
       $.getJSON("/my/ajax/controller/bar?data[bar_number]=" + query + "&data[foo_name]=" + fooName, function(response) { 
        add(response); 
       }) 
     }], 
    }); 
}); 
相關問題