动态选择框无法在Jquery onchange

时间:2020-01-15 22:25:10

标签: php jquery html ajax typeahead

我在项目上使用Twitter TypeAhead plugin,我想修改脚本以正确填充输入文本。我发现了类似的问题,但不幸的是我没有找到解决此问题的正确方法:

  1. Dynamically populating Twitter Bootstrap Typeahead
  2. populate select box based on the another select box
  3. populate select box on selecting another selectbox

基于上面的描述并作为参考,我创建了一个显示我怀疑的HTML页面:http://testsitex2019.000webhostapp.com/

首先,我将显示MySql表,该表调用(产品),其中包含填充到输入文本中的记录:

id | categoryFK (Foreing Key) | ProductName   | image
--------------------------------------------------------
01 | 1 (Shoes)                | Adidas Shoes  | img_01
02 | 1 (Shoes)                | Nike Shoes    | img_02
03 | 1 (Shoes)                | Red Tenis     | img_03
04 | 2 (Clothes)              | Black Jacket  | img_04
05 | 2 (Clothes)              | Blu T-shirt   | img_05

现在,我将显示显示的html代码:

  1. 一个选择框,其中装有php代码( #category );
  2. 使用TypeAhead插件( #products )填充的输入文本;
  3. 还有一个div( #image ),当用户在输入文本( #products )中选择一个选项时,该div显示一个值。
<!DOCTYPE html>
<html lang="en">
<head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">

<!-- CSS library -->
<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" style="max-width:1230px;">
<h1>DYNAMIC BOOTSTRAP TWITTER TYPEAHEAD</h1>
<hr>
<br>
<div class="row">

<?php 
    // Include the database config file 
    include_once 'dbConfig.php'; 

    // Fetch all the category data 
    $query = "SELECT * FROM categories ORDER BY category ASC"; 
    $result = $db->query($query); 
?>

<!-- category dropdown -->
<div class="col-md-2">
    <label>Categories</label>
<select id="categoryFK" name="categoryFK" class="form-control">
    <option value="">select category</option>
    <?php 
    if($result->num_rows > 0){ 
        while($row = $result->fetch_assoc()){  
            echo '<option value="'.$row['categoryID'].'">'.$row['category'].'</option>'; 
        } 
    }else{ 
        echo '<option value="">Category not available</option>'; 
    } 
    ?>
</select>
</div>

<div class="col-md-4">
<label>Product name</label>
<input type="text" name="products" id="products" class="form-control input-lg typeahead" autocomplete="off" placeholder="Select category and then type product name here" />

</div>

<div class="col-md-6">
<label>(<i>The image name will be display here after select TypeAhead value</i>)</label>
<div id="image" class="image" name="image" height="15px" style="background-color:#f2f0f0;"></div>

</div>
</div>
</div>

下面是TypeAhead和Ajax脚本,其中Ajax脚本向php脚本发送请求,接收响应并将数据发送到TypeAhead填充输入文本:

<script>
$(document).ready(function(){
var products;
var names = []; // array
var list = {}; // object

$('#categoryFK').on('change', function(){

var queryID = $(this).val();

   $.ajax({
    url:"fetch.php",
    method:"POST",

    data:{category:queryID},
    dataType:"json",
success:function(data){
console.log(data);

$.each(data, function(i, optionHtml){
              $('#products').append(optionHtml);
           });

$(".typeahead").val ('');
$( ".image" ).empty();
products = data;

 }
 });

 $('.typeahead').typeahead({

  source: function(query, result)
  {
   $.each(products, function(idx, item){

      if(!~names.indexOf(item.productName)) names.push(item.productName);
      list[item.productName] = item.image;
   });
   return result(names);
},
  afterSelect: function (data) {
  var tmp = list[data];

   $('#image').html(tmp);

},

 });

}); 
});
</script>

最后,接收Ajax请求并以JSON发送结果的php脚本( fetch.php ):

<?php
require_once '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;

        }

 header("Content-type: application/json; charset=utf-8 cache-control: no-cache, no-store, must-revalidate");
 echo json_encode($data);
 exit();
    }
}
?>

疑问:当用户选择类别选择框( #category )时,TypeAhead输入文本( #products )会填充与所选类别ID相关的记录。

首次出现这种情况时,将正确填充输入文本,但是当用户在不刷新页面的情况下将类别值输入到选择框( #category )中时,预输入文本( #products )将填充有product表中的所有记录,而不是仅填充与所选类别ID相关的记录。

在此page that i created中,您可以看到上面所有代码的工作方式,但是我没有正确的方法来修改脚本以正确填充TypeAhead输入文本。

0 个答案:

没有答案