Jquery:如何将搜索结果分配给输入?

时间:2014-12-25 20:13:45

标签: php jquery mysqli autocomplete

当我点击其中一个结果时,我想将搜索结果分配给输入值(自动完成)。我该怎么做?我的工作代码如下。

HTML(index.php)

<span id="box">       
<label for="search_box">Type the writer's name</label>  
<input type="text" name="book_writer_name" id="book-writer-name">                   
</span>                    
<div id="search_result"></div>
<script src="/jquery/jquery-2.1.1.js"></script>
<script src="/jquery/jquery-ui-1.9.2.custom.js"></script>
<script src="edit.js" type="text/javascript"></script>

jQuery(edit.js)

$(document).ready(function () {
    var left = $('#box').position().left;
    var top = $('#box').position().top;
    var width = $('#box').width();

    $('#search_result').css('left', left).css('top', top + 32).css('width', width);

    $('#book-writer-name').keyup(function() {
       var value = $(this).val();
        if(value != '') {
            $.post('search.php', {value:value}, function(data) {
                $('#search_result').html(data);
            });
        }
    });
});

PHP(search.php)

require('../../../cn/connect.php');
$value = htmlspecialchars($_POST['value']);
$value = mysqli_real_escape_string($sqli, $value);
$query = mysqli_query($sqli, "SELECT writer_name from writer where writer_name like '$value%' LIMIT 20");
while ($run = mysqli_fetch_array($query)) {
    $writer_name = $run['writer_name'];
    echo '<a href=#>'.$writer_name.'</a><br>';
}

1 个答案:

答案 0 :(得分:1)

将此添加到文档就绪部分:

$('#search_result').on('click', 'a', function(){
     $('#book-writer-name').val($(this).text());
});

如果我理解得很清楚,那么在点击结果链接后,你会尝试为输入字段添加值。