[英]how to auto complete cities list based on entered state name in PHP MySQL and JQuery
I am able to auto fill(complete) states and cities textboxes independently using below mentioned script. 我能够使用下面提到的脚本独立自动填充(完整)州和城市文本框。
But I want to do following. 但是我想做以下。
First I enter state name in state textbox and select any state from suggested states list. 首先,我在状态文本框中输入状态名称,然后从建议的状态列表中选择任何状态。
There after I enter city name in city textbox but at that time suggested cities list should be filtered according to selected state. 在此之后,我在城市文本框中输入城市名称,但此时建议的城市列表应根据所选状态进行过滤。
For Example: First I enter/select 'New York' in state textbox, after that when I enter city name in city textbox then I should get suggest cities list only for 'New York' state. 例如:首先,我在州文本框中输入/选择“纽约”,然后,当我在城市文本框中输入城市名称时,我应该得到仅针对“纽约”州的建议城市列表。
Please let me know what changes I need to do in script to get desired result. 请让我知道我需要在脚本中进行哪些更改才能获得所需的结果。
NOTE: statepkid field is available in tr_cities table for relation. 注意:tr_cities表中的statepkid字段可用于关联。
index.php 的index.php
<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>
<script>
$(function() {
$( "#statename" ).autocomplete({
source: 'search.php'
});
});
$(function() {
$( "#cityname" ).autocomplete({
source: 'c_search.php'
});
});
</script>
<div class="ui-widget">
<label for="statename">State: </label>
<input id="statename">
<label for="cityname">City: </label>
<input id="cityname">
</div>
search.php (for states) search.php(用于状态)
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = 'password';
$dbName = '10000dbname';
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$searchTerm = $_GET['term'];
$query = $db->query("SELECT * FROM tr_states WHERE statename LIKE '%".$searchTerm."%' ORDER BY statename ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['statename'];
}
echo json_encode($data);
c_search.php (for cities) c_search.php(适用于城市)
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = 'password';
$dbName = '10000dbname';
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$searchTerm = $_GET['term'];
$query = $db->query("SELECT * FROM tr_cities WHERE city LIKE '%".$searchTerm."%' ORDER BY city ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['city'];
}
echo json_encode($data);
In your JS 在你的JS里
source: 'c_search.php?state=' + $('#statename').val()
and in php file 并在php文件中
I am assuming that the column name is state_id
in you city table. 我假设您的城市表中的列名称为
state_id
。
if(isset($_GET['state'])){
$stateid = $_GET['state'];
$query = $db->query("SELECT * FROM tr_cities WHERE city LIKE '%".$searchTerm."%' AND state_id = ".$stateid." ORDER BY city ASC");
}else{
$query = $db->query("SELECT * FROM tr_cities WHERE city LIKE '%".$searchTerm."%' ORDER BY city ASC");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.