AJAX在动态字段上自动完成

时间:2016-01-26 14:19:56

标签: javascript php jquery ajax autocomplete

我有一个工作代码,其中如果我可以添加最多10个输入字段。另外,我需要将这些输入字段与ajax自动完成合并,但只有第一个输入字段有效。

这是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>

添加动态输入字段:

<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代码:

<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>

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 } } ?>

如何使用AJAX为我添加的每个输入字段进行自动完成?我应该在代码中添加什么?请帮我。非常感谢你。

1 个答案:

答案 0 :(得分:1)

您永远不会添加任何&#39; keyup&#39;动态输入字段上的监听器。

您可以将ajax帖子包装到名为autoComplete的函数中。例如。

然后在创建元素时,只需在keyup事件上调用该函数。

编辑: 另外,我注意到你添加了如下的硬ID:

<input id="search_resp1" 

我认为它应该像

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

编辑2:

添加动态输入字段:

$(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代码:

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

您可能希望用于显示结果的div在您点击外部时隐藏。

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

这只隐藏了您的第一个建议框。我建议你在你的div上用id&#34; resp _&#39; + x&#39;&#34;和建议框然后隐藏它:

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