在选择框中显示数据取决于另一个基于搜索的数据

时间:2017-12-21 09:55:42

标签: javascript php jquery html ajax

我有一个文本框。其中,当我键入任何字母表时,相关的是,一些数据显示在下拉列表中,当我从下拉列表中选择任何数据时,那么相关的数据应该在另一个选择框中显示另一些数据。我有一些代码。但它不起作用。

下面是两个div,一个是 selectcity ,另一个是 selectarea

的index.php

<div class="col-xs-12 col-sm-6 col-md-3">
    <div class="form-group mb-15">
        <input type="text" 
               name="selectcity" 
               id="selectcity" 
               class="selectcity tt-query" 
               autocomplete="off" 
               spellcheck="false" 
               placeholder="Type your city">
    </div>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
    <div class="form-group mb-15" >
        <select required id="selectarea" class="form-control" name="selectarea">
            <option value="">Select Area</option>
        </select>
    </div>
</div>

脚本文件是:

<script src="typeahead.min.js"></script>
<script>
    $(document).ready(function() {
        $('input.selectcity').typeahead({
            name: 'selectcity',
            remote: 'search.php?key=%QUERY',
            limit: 10
        });
    });
</script>

<!-- end for ajax live search, for city -->

<script type="text/javascript">
    $(document).ready(function() {
        $("#selectcity").change(function() {
            var selectedcity = $(this).val();
            $.ajax({
                type: "POST",
                url: "process-request.php",
                data: "selectcity=" + selectedcity,
            }).done(function(data) {
                $("#selectarea").html(data);
            });
        });
    });
</script>

search.php是:

<?php
    include("connection.php");
    $key=$_GET['key'];
    $array = array();

    $query=mysql_query("select * from location_master where status1='1' AND location LIKE '%{$key}%'");
    while($row=mysql_fetch_assoc($query))
    {
      $array[] = $row['id'];
    }
    echo json_encode($array);
?>   

process-request.php是:

<?php
    include("connection.php");

    if(isset($_POST["selectcity"])){
        $selectcity = $_POST["selectcity"];

        $query1=mysql_query("select * from location_master where parent_id='$selectcity'") or die (mysql_error());

       if($selectcity !== 'Select City'){
           echo"<option value=''>Select Area</option>";
           while($value = mysql_fetch_array($query1)) {
?>
                <option value="<?php echo $value['id'];?>" ><?php echo $value['location'];?></option>
<?php
           }
       } 
   }
?>

1 个答案:

答案 0 :(得分:0)

使用typeahead回调代替:

$(document).ready(function() {
    $('input.selectcity').typeahead({
        name: 'selectcity',
        remote: 'search.php?key=%QUERY',
        limit: 10
    }).on('typeahead:selected', function(e){
        var selectedcity = $(this).val();

        $.ajax({
            type: "POST",
            url: "process-request.php",
            data: "selectcity=" + selectedcity,
        }).done(function(data) {
            $("#selectarea").html(data);
        });
    });
});