【问题标题】:php: multiple select box in a array with search functionphp:具有搜索功能的数组中的多个选择框
【发布时间】:2015-02-11 11:30:36
【问题描述】:

我有选择框数组,根据我想显示的选择框数量输出多个选择框。我选择该选项时的功能是它使用 ajax 在我的数据库中搜索房间详细信息。搜索功能有效,但仅在第一个选择框中有效,不适用于我的其余选择框。 这是 mypage.php

<select name = "room[]" id = "search">
  <option value = "none">&larr;Room</option>
  <?php
    $find_room = DB::getInstance()->query("SELECT * FROM tbl_room WHERE room_status =  'ENABLED'");
if($find_room->count()){
   foreach($find_room->results() as $find_room){

    ?>
     <option value = "<?php echo $find_room->room_id; ?>"><?php echo $find_room->room_number; ?>
     </option>
 <?php

    }
  } 
  ?>
</select>

这是我的 ajax

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

    $("#search").change(function(){
        var search = $("#search").val();
        $.ajax({
            type:"POST",
            url:"programhead_ajaxroom.php",
            data:{search:search},
            success:function(res){
                $("#subjects").html(res);
            }

        });
    });
 });
</script>

这是我的ajax页面

if(isset($_POST['search'])){
 functions right here are select querys into table(this is working)
}

非常感谢您的帮助。

【问题讨论】:

    标签: php arrays ajax


    【解决方案1】:

    在动态更改 HTML 时尝试使用委托事件的语法。使用 class 属性定义 change 事件并在函数内部使用 this,因为您有很多选择框。

    $(document).on("change",".search",function(){
        ele = $(this);
        var search = ele.val();
        $.ajax({
            type:"POST",
            url:"programhead_ajaxroom.php",
            data:{search:search},
            success:function(res){
                ele.html(res);
            }
    
        });
    });
    

    您还必须在 select html 中使用类属性,因为 ID 应该是唯一的。

    <select name = "room[]" id = "search" class="search">
    

    【讨论】:

    • 选择框的其余部分现在正在响应,但它正在返回第一个选择框的值。
    • @StiEdu , 所有的选择框都有相同的 id "serch" 吗?
    • 是的,先生。因为它在数组中,名称为“room[]”,id 为“search”。假设我想输出多个选择框,具体取决于我想显示多少。示例我仅显示 3 个选择框,内存分配后面的名称将是房间 [0]、房间 [1]、房间 [2]。无论如何,我可以通过它的名称而不是 id 来获取选择框的值吗?
    • 是的,你可以。检查这个问题:stackoverflow.com/questions/1107220/…。 id 也应该是唯一的。您也可以使用 room[x] 之类的东西作为 ids 的值...
    【解决方案2】:

    好吧,我错过的是循环遍历每个元素数组

     $(document).on("change","select[name^=search]",function(){
            check_obj = document.getElementsByName("search[]");
            for (i=0; i<check_obj.length; i++)
            {
                if (check_obj[i].value == "none")
                {}
                else{
                    var search= check_obj[i].value;
                }
            }
            $.ajax({
                type:"POST",
                url:"programhead_ajaxroom.php",
                data:{search:search},
                success:function(res){
                    $("#subjects").html(res);
                }
    
                });
    
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多