如何根据选择框的值填充Twitter Typeahead?

huangapple go评论72阅读模式
英文:

How to populate Twitter Typeahead based on select box value?

问题

这是您提供的代码的中文翻译:

我有一个已正确填充Twitter Typeahead的输入文本。在这种情况下,我想要从选择框中选择一个值,并使用与所选下拉列表值相关的值填充输入文本。我找到了与我的疑惑类似的问题,但不幸的是我没有找到正确的解决方法:

以下是显示带有PHP代码填充的选择框和使用Twitter TypeAhead脚本填充的输入文本的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">

    <!-- CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>   

</head>

<body>

<div class="container">

<br>

<h1>DYNAMIC TWITTER TYPEAHEAD</h1>

<br>
<div class="row">

<?php 
    // 包括数据库配置文件
    include_once 'dbConfig.php'; 
    
    // 获取所有类别数据
    $query = "SELECT * FROM categories ORDER BY category ASC"; 
    $result = $db->query($query); 
?>


<!-- 类别下拉框 -->
<div class="col-md-4">
<select id="categoryFK" name="categoryFK" class="form-control">
    <option value="">选择类别</option>
    <?php 
    if($result->num_rows > 0){ 
        while($row = $result->fetch_assoc()){  
            echo '<option value="'.$row['categoryID'].'">'.$row['category'].'</option>'; 
        } 
    }else{ 
        echo '<option value="">类别不可用</option>'; 
    } 
    ?>
</select>
</div>

<div class="col-md-4">

<input type="text" name="products" id="products" class="form-control input-lg" autocomplete="off" placeholder="" />

</div>

</div>
</div>


</body>
</html>

以下是通过Ajax调用PHP脚本的脚本:

<script>
$(document).ready(function(){

 $('#categoryFK').on('change', function(){
        var queryID = $(this).val();
 if(queryID){
 $('#products').typeahead({
  source: function(query, result)
  {
   $.ajax({
    url:"fetch.php",
    method:"POST",
    data: 'query='+queryID,
    dataType:"json",
    success:function(data)
    {
     result($.map(data, function(item){
      return item;
     }));
    }
   })
  }
 });
 }
 });
});
</script>

以下是根据categoryID填充值的PHP脚本(fetch.php):

<?php
//fetch.php
include 'dbConfig.php';
if(!empty($_POST["query"])){ 
$request = mysqli_real_escape_string($db, $_POST["query"]);
$query = "
 SELECT * FROM products WHERE productName LIKE '%".$request."%' AND categoryFK = ".$_POST["query"]."
";

$result = $db->query($query); 
$data = array();

if(mysqli_num_rows($result) > 0)
{
 while($row = mysqli_fetch_assoc($result))
 {
  $data[] = $row["productName"];
 }
 echo json_encode($data);
}
}
?>

如您所示,当我在选择框中选择任何选项后,在输入文本中键入内容时,带有Twitter TypeAhead的输入文本只填充一个记录。

在这种情况下,如何改进上面的PHP代码以正确填充与选择框值相关的输入文本?谢谢。

英文:

I have an input text that is correctly populate with Twitter Typeahead. In this case i would like to select a value from select box and populate the input text with values that are related with selected dropdownlist value. I found similar questions about my doubt but unfortunatly i didnt get the correct way to solve this:

  1. https://stackoverflow.com/questions/13829574/dynamically-populating-twitter-bootstrap-typeahead
  2. https://stackoverflow.com/questions/14957152/twitter-bootstrap-typeahead-to-populate-hrefs
  3. https://stackoverflow.com/questions/19538591/jquery-autocomplete-twitter-typeahead-populate-multiple-fields

Below is the code that display a select box that is populate with php code and an input text that is populated with Twitter TypeAhead script:

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;!-- CSS --&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css&quot;&gt;
&lt;!-- jQuery library --&gt;
&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js&quot;&gt;&lt;/script&gt;   
&lt;/head&gt;
&lt;body&gt;
&lt;div class=&quot;container&quot;&gt;
&lt;br&gt;
&lt;h1&gt;DYNAMIC TWITTER TYPEAHEAD&lt;/h1&gt;
&lt;br&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;?php 
// Include the database config file 
include_once &#39;dbConfig.php&#39;; 
// Fetch all the category data 
$query = &quot;SELECT * FROM categories ORDER BY category ASC&quot;; 
$result = $db-&gt;query($query); 
?&gt;
&lt;!-- category dropdown --&gt;
&lt;div class=&quot;col-md-4&quot;&gt;
&lt;select id=&quot;categoryFK&quot; name=&quot;categoryFK&quot; class=&quot;form-control&quot;&gt;
&lt;option value=&quot;&quot;&gt;Select category&lt;/option&gt;
&lt;?php 
if($result-&gt;num_rows &gt; 0){ 
while($row = $result-&gt;fetch_assoc()){  
echo &#39;&lt;option value=&quot;&#39;.$row[&#39;categoryID&#39;].&#39;&quot;&gt;&#39;.$row[&#39;category&#39;].&#39;&lt;/option&gt;&#39;; 
} 
}else{ 
echo &#39;&lt;option value=&quot;&quot;&gt;Category not available&lt;/option&gt;&#39;; 
} 
?&gt;
&lt;/select&gt;
&lt;/div&gt;
&lt;div class=&quot;col-md-4&quot;&gt;
&lt;input type=&quot;text&quot; name=&quot;products&quot; id=&quot;products&quot; class=&quot;form-control input-lg&quot; autocomplete=&quot;off&quot; placeholder=&quot;&quot; /&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

Below is the script that call php script via Ajax:

&lt;script&gt;
$(document).ready(function(){
$(&#39;#categoryFK&#39;).on(&#39;change&#39;, function(){
var queryID = $(this).val();
if(queryID){
$(&#39;#products&#39;).typeahead({
source: function(query, result)
{
$.ajax({
url:&quot;fetch.php&quot;,
method:&quot;POST&quot;,
data: &#39;query=&#39;+queryID,
dataType:&quot;json&quot;,
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
}
});
});
&lt;/script&gt;

And below is the php script (fetch.php) that populate values according to categoryID:


&lt;?php
//fetch.php
include &#39;dbConfig.php&#39;;
if(!empty($_POST[&quot;query&quot;])){ 
$request = mysqli_real_escape_string($db, $_POST[&quot;query&quot;]);
$query = &quot;
SELECT * FROM products WHERE productName LIKE &#39;%&quot;.$request.&quot;%&#39; AND categoryFK = &quot;.$_POST[&quot;query&quot;].&quot;
&quot;;
$result = $db-&gt;query($query); 
$data = array();
if(mysqli_num_rows($result) &gt; 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row[&quot;productName&quot;];
}
echo json_encode($data);
}
}
?&gt;

As i showed the code above, when i type something into input text after i selected any option into select box, the input text with Twitter TypeAhead just populate one register.

In this case, how can i improve php code above to populate input text with values related with select box value correctly? Thanks.

答案1

得分: 0

I managed to solve the problem. Below are the scripts that I modified to adapt to my project:

AJAX

<script type="text/javascript">
	var products;
	$(function () {
		$('#categoryFK').on('change', function () {
			var queryID = $(this).val();

			$.ajax({
				url: "fetch.php",
				method: "POST",
				data: {
					category: queryID
				},
				dataType: "json",
				success: function (data) {
					$("#products").val('');

					products = data;
				}
			});
		});

		$('#products').typeahead({
			source: function (query, result) {
				result($.map(products, function (item) {
					return item;
				}));
			}
		});
	});
</script>

And PHP script (fetch.php)

<?php
include 'dbConfig.php';

if (isset($_POST['category'])) {
	$request = $db->real_escape_string($_POST["category"]);

	$query = "
		SELECT * FROM products WHERE categoryFK = ".$request."
	";

	$result = $db->query($query);
	$data = array();

	if ($result->num_rows > 0) {
		while ($row = $result->fetch_assoc()) {
			$data[] = $row["productName"];
		}

		echo json_encode($data);
	}
}
?>

Now, with these modifications, I can select an option in the "category" select box and then type into the input text where all values related to the selected option will be loaded.

英文:

I managed to solve the problem. Below are the scripts that i modified to adapt on my project:

AJAX

&lt;script type=&quot;text/javascript&quot;&gt;
var products;
$ ( function ()
{
$(&#39;#categoryFK&#39;).on(&#39;change&#39;, function(){
var queryID = $(this).val();
$.ajax({
url:&quot;fetch.php&quot;,
method:&quot;POST&quot;,
data: {
category: queryID
},
dataType:&quot;json&quot;,
success:function(data)
{
$(&quot;#products&quot;).val (&#39;&#39;);
products = data;
}
});
});
$(&#39;#products&#39;).typeahead({
source: function ( query, result )
{
result ( $.map(products, function (item)
{
return item;
}
));
}
});
});
&lt;/script&gt;

And PHP script (fetch.php)

&lt;?php
include &#39;dbConfig.php&#39;;
if ( isset ( $_POST [ &#39;category&#39; ] ) ) {
$request = $db-&gt;real_escape_string($_POST[&quot;category&quot;]);
$query = &quot;
SELECT * FROM products WHERE categoryFK = &quot;.$request.&quot;
&quot;;
$result = $db-&gt;query($query);
$data = array ();
if ( $result-&gt;num_rows &gt; 0 )
{
while($row = $result-&gt;fetch_assoc ())
{
$data[]=$row[&quot;productName&quot;];
}
echo json_encode($data);
}
}
?&gt;

Now, with these modifications, i can select an option into "category" select box and after, type into input text where all valus related with selected option will be load 如何根据选择框的值填充Twitter Typeahead?

huangapple
  • 本文由 发表于 2020年1月6日 22:47:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定