javascript - 根据自动完成文本框中插入的值动态添加下拉列表

标签 javascript php jquery autocomplete

请有人帮忙,我真的被这个问题困扰了两天:|

我有一个 PHP 表单,我希望用户能够按标题或 Actor 选择电影。 因此,我正在考虑按这些值(moviebyTitle、moviebyActor)创建一个下拉菜单。为了按标题选择电影,我使用了 jQuery 自动完成功能,它从我的数据库中获取电影标题,效果很好。

这是我的代码:

<select id="selectType" name="source">
  <option value="">MoviesBy</option>
  <option value="byTitle">byTitle</option>
  <option value="byActor">byActor</option>
</select>

<input type="textbox" name= "tag" id="tags">

<div id="byActor" class="style-sub-1" style="display: none;" name="stylesub1" onchange="ChangeDropdowns(this.value)">
<select name="films[]" multiple="multiple" width="200px" size="10px">
  <?php
   include('moviedropdown.php');
  ?>
 </select>

这是 JavaScript:

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" /> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>

<script type="text/javascript">
$(document).ready(function () {
    $("#tags").autocomplete({
    source: "actorsauto.php",
    minLength: 2
}); 
 $("#selectType").change(function () {
     if ($(this).val() == "byTitle")
        $("#tags").autocomplete("option", "source", "filmsauto.php");
      else 
      if ($(this).val() == "byActor")
        $("#tags").autocomplete({
         source: "actorsauto.php",
         minLength: 2,
         select: function (event, ui){
           var selectedVal = $(this).val(); //this will be your selected value from autocomplete
          // Here goes your ajax call.
           $.post("actions.php", {q: selectedVal, q2: $("#selectType").val()}, function (response){
            // response variable above will contain the option tags. Simply put in the dropdown.
             $("#movieImdbId").html(response);
          });
      }
    });
  }
});
});                 
</script>

编辑:

这是 actions.php:(请参阅上面的 javascript 部分)

<?php
if(isset($_GET['q']) && !empty($_GET['q']) && isset($_GET['q2']) && !empty($_GET['q2']) ){
   // Here goes the cleaning code. Never use the variables received from $_GET and $_POST directly before processing it for malicious code.
$q = $_GET['q'];
$q2 = $_GET['q2'];

//$sql = fetchResults($q, $q2); // Some function which will run a database query and return some records in either object collection or arrays etc.

//I added this part to fetch data from DB
include('imdbConnection.php');
$sql = $conn->prepare('SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q');
$sql->execute(array(':q' => $q));

$html = "";

while($row = $sql->fetchAll(PDO::FETCH_OBJ)){

   $option = '<option value="' . $row->movieImdbId . '">' . $row->movieImdbId . '</option>';

$html = $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>

我的问题:

我只是想知道如何根据用户在文本框中输入的值添加下拉列表。例如,如果用户在自动完成文本框中写下“汤姆·克鲁斯”,则会添加一个下拉列表,显示播放过“汤姆·克鲁斯”的电影。 (我在遇到问题的 JavaScript 代码中做了注释)

我确实搜索了很多,但是所有示例都动态填充一些下拉列表( like this one ,或根据下拉列表中选择的值添加文本框...

请帮忙,我真的不是说有人为我编写代码,我只是想找到任何示例或某种方式来学习如何做到这一点。

谢谢

最佳答案

您应该得到如下所示的内容。

您真正需要的是,当您在自动完成框中键入内容并选择某些内容时,您需要保留该值以供以后使用。之后,您需要使用 ajax 调用来调用服务器(一个 php 脚本),并将自动完成框中的值与下拉列表中的值一起发送(仅当您需要时)。该 php 脚本需要在循环中生成一堆类似以下内容的内容,并将整个 html 保存在变量中。

<option value='v1'>Value1</option> <option value='v2'>Value2</option>

之后,将其发送回调用 ajax 脚本,然后您需要将其作为您要填充的下拉列表中的内容。

这里有一些关于如何完成 JavaScript 部分的示例代码。

<select id="filmsdd" name="films[]" multiple="multiple" width="200px" size="10px">

 </select>
<script>
    $(document).ready(function () {
        $("#tags").autocomplete({
          source: "actorsauto.php",
          minLength: 2,
          select: function (event, ui){
              var selectedVal = $(this).val(); //this will be your selected value from autocomplete
              // Here goes your ajax call.
              $.post("actions.php", {q: selectedVal, q2: $("#selectType").val()}, function (response){
                // response variable above will contain the option tags. Simply put in the dropdown.
                $("#filmsdd").html(response);
              });
          }
        });
    });
<script>

编辑:

path/to/somefile.php将是与其他网站文件一起存储在您的目录中的任何文件。我们称之为actions.php (我已经更新了 $.post ajax 调用)

何时 $.post运行时,它会向 actions.php 发送请求以及两个变量 qq2 。这些变量名称可以是任何名称。

q包含从自动完成框中选择的值。 q2包含从下拉列表中选择的类型。

actions.php ,你最终会得到这样的结果。

if(isset($_GET['q']) && !empty($_GET['q']) && isset($_GET['q2']) && !empty($_GET['q2']) ){
   // Here goes the cleaning code. Never use the variables received from $_GET and $_POST directly before processing it for malicious code.
$q = $_GET['q'];
$q2 = $_GET['q2'];

$sql = fetchResuls($q, $q2); // Some function which will run a database query and return some records in either object collection or arrays etc.

// Initialize a variable that you will send back to your ajax call, its still waiting for this script to be completed.
$html = "";

// Assuming your function returned a list of objects. Loop through the records.
while($row = mysql_fetch_object($sql)){
   $option = '<option value="' . $row->property_id . '">' . $row->property_name . '</option>';
$html .= $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}

我希望这会有所帮助。

关于javascript - 根据自动完成文本框中插入的值动态添加下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26411332/

相关文章:

javascript - 机器人框架 : How to add user-confirmation step to CancelAndHelpDialog

php - 如何使用 php 在 excel 表上重复输出

php - 从 MySQL 数据库选择数据时出错

javascript - iPad 中加载框架时的 window.open() 不起作用

javascript - 在用户滚动时加载 chart.js

javascript - 提交ajax后如何清理表单?

javascript - 使用 Javascript 显示和隐藏文本

php - 我可以获得最后插入行的列吗?

jquery - 多个图像相互加载

javascript - 单击reactjs中的按钮时不显示任何文本