根据另一个下拉选择过滤下拉列表

时间:2017-11-03 18:42:05

标签: javascript php jquery html drop-down-menu

我有2个单独的下拉列表。我需要让每个下拉列表互相过滤。到目前为止,我看到的每个示例都是下拉列表的示例,其中包含硬编码的选项。我使用查询来填充选项。

那么我怎样才能正确地让每个下拉菜单相互过滤?

以下是index.php下拉列表的HTML:

<select id="collector" onchange="showUser(this.value)">             
    <option value="" selected disabled>Collector Name</option>
        <?php foreach($collect->fetchAll() as $name) { ?>
    <option class="<?php echo $name['Collector Name'];?>" value="<?php echo $name['Collector Name'];?>"><?php echo $name['Collector Name'];?></option>
        <?php } ?>
    </select>

<select id="date" onchange="showUser(this.value)">              
    <option value="" selected disabled>Bill Date</option>
        <?php foreach($bill_date->fetchAll() as $date) { ?>
    <option class="<?php echo $date['Date'];?>" value="<?php echo $date['Collector Name'];?>"><?php echo $date['Date'];?></option>
        <?php } ?>
    </select>

每次scriptindex.php代码中的下拉列表更改时运行的代码:

function showUser(str) {
  if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;

            var newTableObject = document.getElementById('billing_table');
            sorttable.makeSortable(newTableObject);

        }
        }

    // ---- Gets value of collector dropdown selection -----
        var e = document.getElementById("collector").value;

        $.ajax({
         type: 'GET',
         url: 'index.php',
         data: e,
         success: function(response) {
             console.log(e);
         }
       });                  

    // ---- Gets value of the current selection in any of the dropdowns ----    
        xmlhttp.open("GET","dropdown-display.php?q="+str,true);
        xmlhttp.send();

        document.getElementById('billing_table').style.display = 'none';
    }

$(document).ready(function(){ 
    var $select1 = $( '#collector' ),
        $select2 = $( '#date' ),
    $options = $select2.find( 'option' );

$select1.on( 'change', function() {
    $select2.html( $options.filter( '[value="' + this.value + '"]' ) );
}).trigger( 'change' );


});

在我的index.php页面上查询:

$collector = "SELECT [Collector Name]
  FROM [vSpecial_Billing]
  Group By [Collector Name]";

$billdate = "SELECT [Collector Name], [Date]
  FROM [vSpecial_Billing]
  Group By [Collector Name], [Date]";

我不想将该值发送到我的dropdown-display.php页面,因为填充下拉列表的查询位于我的index.php页面上。但是,如果我将值变量放在查询中,那么它会在加载选择之前运行该查询,然后不会填充我的账单日期下拉列表。

修改

  • 我将日期下拉选项中的value更改为收藏家名称而不是日期
  • 我还在中间代码块
  • 的末尾添加了$(document).ready(function()
  • 我更新了我正在使用的查询

现在可以正确过滤,但是,在页面加载时,无法选择帐单日期。它没有填充任何行。我怎么能改变这个?

此外,当我过滤它时,它默认为列表中的最后一个日期。如何将其默认为硬编码值,例如&#34;日期&#34;然后用户可以从过滤后的值中选择吗?

1 个答案:

答案 0 :(得分:1)

我使用一些示例数据编写了一个测试用例,并确保其有效。这是一个粗略的例子,但我相信它做你需要的。在工作中少了很多。对不起,但是我使用了完整的jquery,因为我再也不用去做长手j啦了哈哈(加上我真的不能按照你在那里发生的事情)。

需要有两个文件:index.phpindex-ajax.php(为清晰起见)

index.php简介:

// note: these do not need to be in prepared statements (theres no variables inside)
$collect  = $db->query("SELECT DISTINCT [Collector Name] FROM [vSpecial_Billing]");
$names    = $collect->fetchAll();
$billdate = $db->query("SELECT DISTINCT [Date] FROM [vSpecial_Billing]");
$dates    = $billdate->fetchAll();
?>

<form id="testForm" action="">
    <select id="collector">             
        <option value="" selected="selected" disabled="disabled">Collector Name</option>
        <?php foreach($names as $name) { ?>
            <option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"><?php echo $name['Collector Name'];?></option>
        <?php } ?>
    </select>
    <select id="date">              
        <option value="" selected="selected" disabled="disabled">Bill Date</option>
        <?php foreach($dates as $date) { ?>
            <option class="choice" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
        <?php } ?>
    </select>
    <input type="button" id="clearchoices" name="clearchoices" value="Clear Choices" />
</form>

上面要注意的一些事项:

  • 您只需要通过DISTINCT选择。无需使用GROUP BY来获取所有唯一名称或所有唯一日期。
  • 我把fetchAll的结果放在变量中,出于习惯,但如果你愿意,你可以把它们移到foreach中。
  • 我删除了您拥有的class定义,因为其中包含空格的类(在收集器名称的情况下)可能是错误的。
  • “清除选择”按钮只是在过滤和过滤超出您选择范围后如何重置这些选择的示例。

这是javascript部分(它在您的表单之前或之后或者在头部中的index.php中):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="Javascript" type="text/javascript">
$(document).ready(function(){

    $("#collector").change(function(e){
        $.post('index-ajax.php',{filter:'Name',by:$(this).val()},function(data){
            $("#date .choice").hide();
            $.each(data, function(key,row) {
       //       $("#date option[value='"+ row.item +"']").show();
                $("#date option").filter(function(i){
                    return $(this).attr("value").indexOf( row.item ) != -1;
                }).show();
            });
        },"JSON");
    });
    $("#date").change(function(e){
        $.post('index-ajax.php',{filter:'Date',by:$(this).val()},function(data){
            $("#collector .choice").hide();
            $.each(data, function(key,row) {
        //      $("#collector option[value='"+ row.item +"']").show();
                $("#collector option").filter(function(i){
                    return $(this).attr("value").indexOf( row.item ) != -1;
                }).show();
            });
        },"JSON");
    });
    $("#clearchoices").click(function(e){ e.preventDefault();
        $("#collector .choice").show(); $("#collector").val('');
        $("#date .choice").show(); $("#date").val('');
    });

});
</script>

这个块需要大量的解释,因为我把你所有的长手javascript打包并装入jquery。

  • 每个select在更改时都有自己的处理程序事件。
  • 每个选择都会自己发布ajax,并使用不同的变量定义来过滤。
  • ajax返回后,它会隐藏OTHER选择中的所有选项。然后启用ajax调用的json数据返回的所有选项。这可以用不同的方式处理,但我想提出一种方法。
  • 关键是为"JSON"方法的返回处理程序设置.post()。您将在index-ajax.php
  • 中了解原因

现在索引-ajax.php:

if (isset($_POST['filter']) and isset($_POST['by'])) {// sanity check

    $results = array();

    if (!empty($_POST['by'])) {
        // these _DO_ need to be in prepared statements!!!
        if ($_POST['filter'] == 'Name') { $sql = "SELECT DISTINCT [Date] as item FROM [vSpecial_Billing] WHERE [Collector Name] = ?"; }
        if ($_POST['filter'] == 'Date') { $sql = "SELECT DISTINCT [Collector Name] as item FROM [vSpecial_Billing] WHERE [Date] = ?"; }
        $stmt = $db->prepare($sql);
        $stmt->execute(array($_POST['by']));
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $results[] = $row; }
    }

    echo json_encode( $results );
    exit;
}

这段代码实际上非常简单。它所做的就是确定要执行哪个过滤操作,准备sql,然后抓取不同的匹配行以进行输出。关键是它输出为json,所以调用它的javascript可以更轻松地处理数据!

现在......我已经在测试脚本中构建了所有这些,而我的服务器讨厌&#34; fetchAll&#34;,所以你的milage可能会因某些数据库代码而异。我还遗漏了所有其他表单代码和数据库设置处理程序以及所有这些。弄清楚你有把握。

我希望这会以某种方式帮助你。

编辑11/7

我做了一个小小的改动,因为我没有意识到你的数据库中的收集器名称会有破坏所有这些的字符,哎呀。奇数字符处理的两个变化:

  • select collector的{​​{1}}值包含在option中。
  • 每个htmlspecialchars() jquery事件过滤器的select部分现在通过查找匹配的索引进行过滤,使用.change作为直接变量。以前,它是在row.item匹配中使用它,如果value=' row.item '有单引号(或其他不良字符),它会破坏整个js事件并失败!

通常当我设置这样的东西时,我使用ID和唯一的元素id标签。这样我只会引用数字,而不会遇到奇怪的字符混搭。将所有内容都转换为ID的示例将会涉及到,我认为您现在有了最新进展的要点。