简体   繁体   English

动态字段上的AJAX自动完成

[英]AJAX autocomplete on dynamic fields

I have a working code wherein if I can add input fields up to 10. Also, I need those input fields to be incorporated with an ajax autocomplete however, only the first input field works. 我有一个工作代码,如果我最多可以添加10个输入字段,那么我还需要将这些输入字段与ajax自动完成功能结合在一起,但是,只有第一个输入字段可以工作。

Here is the html code: 这是html代码:

<div class="item form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12">Respondent <span class="required">*</span></label>
    <div class="col-md-6 col-sm-6 col-xs-12">
        <input id="search-box" class="form-control col-md-5 col-xs-12" name="respondent[]" required="required" type="text">
        <div id="suggesstion-box"></div>
    </div>
</div>
<div class = 'd'></div>

Adding dynamic input fields: 添加动态输入字段:

<script>
        $(document).ready(function() {
            var max_fields      = 10; //maximum input boxes allowed
            var wrapper         = $(".d"); //Fields wrapper
            var add_button      = $("#add_field_button"); //Add button ID


            var x = 1; //initlal text box count
            $(add_button).click(function(e){ //on add input button click
                e.preventDefault();
                if(x < max_fields){ //max input box allowed
                    x++; //text box increment
                    $(wrapper).append('<div class="item form-group"><label class="control-label col-md-3 col-sm-3 col-xs-12">Respondent <span class="required">*</span></label><div class="col-md-6 col-sm-6 col-xs-12"><input id="search_resp1" class="form-control col-md-5 col-xs-12" name="respondent[]" required="required" type="text"/> <div id="resp1"></div> </div><a href="#" class="remove_field">Remove</a></div>'); //add input box
                }
            });

            $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
                e.preventDefault(); $(this).parent('div').remove(); x--;
            });

        });
</script>

AJAX CODE: AJAX代码:

<script>
        $(document).ready(function(){
            $("#search-box").keyup(function(){
                $.ajax({
                type: "POST",
                url: "../search/docrequest_search.php",
                data:'keyword='+$(this).val(),
                beforeSend: function(){
                    $("#search-box").css("background","#FFF");
                },
                success: function(data){

                    if (data == 0) {
                        $("#suggesstion-box").html('<ul style="width: 550px; position: absolute; top: 100%;  z-index: 10;" id="country-list"><li>No match found.</li></ul>');

                    }
                    else {
                        $("#suggesstion-box").show();
                        $("#suggesstion-box").html(data);
                        $("#search-box").css("background","#FFF");

                    }

                }
                });
            });
        });
        $(document).click( function(){

            $('#suggesstion-box').hide();
        });
        function selectCountry(val) {
        $("#search-box").val(val);
        $("#suggesstion-box").hide();
        }
    </script>

EXTERNAL PHP CODE FOR AJAX: AJAX的外部PHP代码:

<?php
      require_once("dbcontroller.php");
      $db_handle = new DBController();

      if(!empty($_POST["keyword"])) {
           $query ="SELECT * FROM person WHERE (firstName like '" . $_POST["keyword"] . "%' OR lastName like '" . $_POST["keyword"] . "%') AND residentOrNot = 'Yes' AND income != 0";
           $result = $db_handle->runQuery($query);

      if(!empty($result)) {
  ?>
    <ul id="country-list" style = "width: 550px; position: absolute; top: 100%; margin: 0;  z-index: 10; padding: 0;">
    <?php
    foreach($result as $country) {
    ?>
    <li onClick="selectCountry('<?php echo $country["idPerson"]?>');">Name: <?php echo $country["firstName"].' '.$country["middleName"].' '.$country["lastName"]; ?><br> ID: <?php echo $country["idPerson"]; ?></li>
    <?php } ?>
    </ul>
    <?php } } ?>

How can I make autocomplete using AJAX work for every input field I add? 如何为添加的每个输入字段使用AJAX进行自动完成? What should I add in my code? 我应该在代码中添加什么? Please help me. 请帮我。 Thank you so much. 非常感谢。

You never add any 'keyup' listener on your dynamic input fields. 您永远不会在动态输入字段上添加任何“ keyup”侦听器。

You could wrap your ajax post into a function called autoComplete for example. 例如,您可以将ajax帖子包装到一个名为autoComplete的函数中。

Then when you create an element, you just call that function on keyup event. 然后,当您创建元素时,只需在keyup事件上调用该函数。

Edit : Also, I noticed that you add hard IDs like : 编辑:另外,我注意到您添加了硬ID,例如:

<input id="search_resp1" 

I think it should be something like 我认为应该是这样

<input id="search_resp'+ x +'" 

Edit 2 : 编辑2:

Adding dynamic input fields : 添加动态输入字段:

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".d"); //Fields wrapper
    var add_button      = $("#add_field_button"); //Add button ID


    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div class="item form-group">'
                                    +'<label class="control-label col-md-3 col-sm-3 col-xs-12">'
                                    +'    Respondent <span class="required">*</span>'
                                    +'</label>'
                                    +'<div class="col-md-6 col-sm-6 col-xs-12">'
                                    +'    <input id="search_resp_'+x+'" class="form-control col-md-5 col-xs-12" name="respondent[]" required="required" type="text"/>'
                                    +'    <div id="resp_'+x+'"></div> '
                                    +'</div>'
                                    +'<a href="#" class="remove_field">Remove</a>'
                               +'</div>'); //add input box
        }
    });


    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); 
        $(this).parent('div').remove(); 
        x--;
    });

    // The same way you added the above click event listener in order to
    // remove the textbox, you add a keyup event listener on the new input
    // and call autoComplete (which contains your ajax request)
    $("#search_resp_"+x).keyup(
        function(){
            autoComplete();
        });
});

AJAX CODE : AJAX代码:

function autoComplete(){
    $.ajax({
        type: "POST",
        url: "../search/docrequest_search.php",
        data:'keyword='+$(this).val(),
        beforeSend: function(){
            $(this).css("background","#FFF");
        },
        success: function(data){

            if (data == 0) {
                $(this).next().html('<ul style="width: 550px; position: absolute; top: 100%;  z-index: 10;" id="country-list"><li>No match found.</li></ul>');
            }
            else {
                $(this).next().show();
                $(this).next().html(data);
                $(this).css("background","#FFF");
            }
          // $(this) should be you textbox
          // and $(this).next() will return the div next to your textbox
          // which is, I guess, the div used for displaying the results
        }
    });
}

$(document).ready(function(){
    $("#search-box").keyup(function(){
        autoComplete();
    });
});

You may want your div used to display the results to hide when you click outside. 您可能希望在单击外部时将用于显示结果的div隐藏。

$(document).click( function(){
            $('#suggesstion-box').hide();
        });

This only hides your first suggestionbox. 这只会隐藏您的第一个意见箱。 I suggest you had a class to your div with the id "resp_'+x'" and suggestion box and then hide it : 我建议您在div上创建一个类,其ID为“ resp _'+ x'”和建议框,然后将其隐藏:

$(document).click( function(){
            $('.your_class').hide();
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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