简体   繁体   中英

php: multiple select box in a array with search function

I have arrays of select box which will output multiple select box depending on how many select box i wanna show. The function when i select the option is that it search room details in my database using ajax. The search function works but only in the first select box not for the rest of my select boxes. this is 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>

this is my 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>

this is my ajaxpage

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

I really appreciate your help.

Try using syntax for delegated event as you are dynamically changing HTML. Use the class attribute to define the change event and use this inside the function as you have many select boxes.

$(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);
        }

    });
});

Also you have to use a class attribute in select html as IDs are supposed to be unique.

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

oh well, what i missed is looping through every array of element

 $(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);
            }

            });

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM