当用户从自动完成中选择数据时,在输入字段中添加文本

时间:2017-09-07 17:19:59

标签: jquery ajax autocomplete

  

当用户在输入字段列表中搜索自动完成时使用ajax问题是单击文本而不是文本而不是在输入字段中添加因为数据是动态的,例如我点击lenova时我点击它无法在输入字段中设置

的index.php
     

<div class="form-group has-success has-feedback">
  <label class="col-sm-3 control-label" for="inputSuccess">Search Here....</label>
  <div class="col-sm-4">
    <input type="text" class="form-control" id="inputSuccess" name="name" onkeyup="autosearch(this.value)" >
    <div class="result" style="width:100%;z-index:100;position: relative;"> 
    </div>
  </div>
  <div class="col-sm-4">
    <input type="text" class="form-control" id="inputSuccess" name="name" onkeyup="autosearch(this.value)" >
    <div class="result" style="width:100%;z-index:100;position: relative;"> 

    </div>
  </div>
</div>

脚本

<script>
 function autosearch(name){

$.ajax({
    url:"ajax.php",
    type:'post',
    data:{name:name},
    success:function(result){
        $('.result').html(result);
    }
   });
}

 </script>
 <script>

 $(document).ready(function()
 {
    $(".result > p").click(function()
    {
        var va1 = $(this).val();
        $("inputSuccess").val(va1); 


    });
});
 </script>

ajax.php

<?php 

$name = $_REQUEST['name'];
$query ="select * from autosearch where autosearch_name like '".$name."%'";
$rs = mysql_query($query,$conn) or die("failed".mysql_error());
while($data = mysql_fetch_assoc($rs)){


<div style="border: 1px solid #ccc;width:100%;" >

            <a href="javascript:void(0)" style="text-decoration: none;" ><div style="width:20%; float:left ;text-decoration: none">
                <img src="image/<?php echo $data['autosearch_image']; ?>" width="80px;" ></div>
                <div style="width:80%;">
                    <p><?php echo $data['autosearch_name']; ?>
                    </p>
                </div>
            </a>
    </div>

 <?php } ?>

1 个答案:

答案 0 :(得分:0)

您可以像这样使用自动完成功能:

              $("#inputSuccess").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "someurl",
                    type: "POST",
                    dataType: "json",
                    data: { term: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.something
                                Name: item.somethingelse,

                            };
                        }));
                    }
                });
            },
            minLength: 3
        });

             $("#inputSuccess").on("autocompleteselect", function (event, ui) {

           $("#someelement").val(data.whatever);   
        });