自动完成搜索框,从结果中选择多个值

问题描述 投票:2回答:1

我正在使用php / mysql创建我自己的食谱盒,而我坚持的一部分实际上是创建食谱,特别是选择成分。

我想要做的是有一个自动完成的搜索框,我可以在其中输入成分的名称,将结果下拉到下面,然后单击我正在寻找的那些。单击该成分后,它将被列在搜索框下方,其中包含输入数量和“x”以在需要时删除。这当然会增长取决于配方需要多少成分。最后,我将获取数据并插入到我的数据库中。

我已经看到很多关于获得自动完成搜索框功能的AJAX教程,但没有任何东西将它与价值选择联系起来。在http://supercook.com可以找到我想要的最好的例子。他们有它,所以你可以搜索食谱。

有什么建议或在线资源吗?

谢谢!

php mysql ajax forms search
1个回答
4
投票

你问了一个很棒的问题。下面我写了一个简短的例子来帮助你入门。只需将其保存为ingredients.php即可。当然,您需要添加数据库连接和查询以提供真实数据。我使用了jQuery库,因为它使Javascript部分更容易。

<?php

// connect to database here

if (isset($_POST['q'])) {
    if (trim($_POST['q']) === '') die('[]');
    // $q = mysql_real_escape_string($_POST['q']);
    // run a query like: "SELECT id, name FROM ingredients WHERE name LIKE '{$q}%'"
    // and put the result in the $result array.
    // This is sample data:
    $result = array(
        array('id' => 71, 'name' => 'apple'),
        array('id' => 3, 'name' => 'anchovies'),
        array('id' => 230, 'name' => 'artichoke'),
        );

    if (function_exists('json_encode')) die(json_encode($result));
    else {
        $escaped = array();
        foreach ($result as $r) $escaped[] = str_replace(array('\\', '"'), array('\\\\', '\"'), $r);
        die('["'.join('","', $escaped).'"]');
    }
}

$data = array();
if (isset($_POST['ingredients'])) {
    foreach ($_POST['ingredients'] as $i => $ingredient) {
        $data[] = array(
            'ingredient' => $ingredient,
            'quantity' => $_POST['quantities'][$i],
            );
    }
    // save data to the database here (or inside the foreach loop above)
}

?>
<html><head></head><body>
<style>
    #wrap { position: relative }
    #pop {
        position: absolute;
        border: 1px solid black;
        background-color: white;
        display: none;
    }
</style>

<?php if (count($data)): ?>
<h3>Saved:</h3>
<pre><?php print_r($data) ?></pre>
<?php endif; ?>

<div id="wrap">
    <input id="adder" />
    <div id="pop"></div>
</div>
<form method="post">
    Ingredients:<br />
    <div id="recipe"></div>
    <input type="submit" value="Save" />
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
    var last_query = '';
    jQuery(function() {
        jQuery('#adder').val('').keyup(function() {
            var query = jQuery(this).val();
            if (query != last_query) jQuery.post('ingredients.php', {q: query}, function(data) {
                var p = jQuery('#pop').html('').show();
                for (var i=0; i<data.length; i++) {
                    p.append(jQuery('<p>'+data[i].name+'</p>').bind('click', { ingredient: data[i] }, function(e) {
                        add_ingredient(e.data.ingredient);
                        jQuery('#pop').hide();
                        jQuery('#adder').val('');
                    }));
                }
            }, 'json');
            else jQuery('#pop').show();
            last_query = query;
        });
    });
    function add_ingredient(data) {
        console.log(data);
        var ingredient = jQuery('<div> <input name="quantities[]" size="2" /> '+data.name
            + '<input type="hidden" name="ingredients[]" value="'+data.id+'" /></div>');
        var remover = jQuery('<span>X</span>').click(function() {
            jQuery(this).parent().remove();
        });
        jQuery('#recipe').append(ingredient.prepend(remover));
    }
</script>
</body></html>
© www.soinside.com 2019 - 2024. All rights reserved.