jQuery没有检测到空输入

时间:2016-10-19 20:45:46

标签: jquery

我正在尝试通过jQuery清除搜索字段后将No results作为输出。但是jQuery从不检测输入seach-field是否为空。

这是jQuery:

<script>
    $(document).ready(function(e){
        console.log("Document loaded!");
        $('#searchbox').each(function() {
            $("#results").html("<a class='dropdown-item' href='#'>No results!</a>");
            var sb = $(this);
            sb.data('oldVal', sb.val());
            sb.bind("propertychange change click keyup input paste", function(event){
                if (sb.data('oldVal') != sb.val()) {
                    var key = $(this).val();
                    console.log(key);
                    if (key == undefined || key == null || !key) {
                        $("#results").html("<a class='dropdown-item' href='#'>No results!</a>");
                    }
                    else {
                        $.ajax({
                            type: 'GET',
                            url: 'search.php',
                            data: 'keyword='+key,
                            success: function(data) {
                                $("#results").html(data);
                            },
                        })
                    }
                }
            });
        }); 
    });
</script>

编辑:需要HTML

<form class="form-inline pull-xs-right hidden-xs-down">
    <input class="form-control" type="search" id="searchbox" name="keyword" placeholder="Zoeken">
    <div id="results"></div>
</form>

和PHP

<?php 
if (empty($_GET['keyword'])) {
    echo "<a class=\"dropdown-item\" href=\"#\">No results!</a>";
}
elseif (!empty($_GET['keyword'])) {
    require_once 'include/config.php';

    $q = mysqli_real_escape_string($mysqli, $_GET['keyword']);
    if ($q == "%" || $q == "") { 
        $q = NULL;
        echo "<a class=\"dropdown-item\" href=\"#\">No results!</a>";
    }
    $sql = "SELECT * FROM producten WHERE naam LIKE '%$q%'";
    $result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
    if (mysqli_num_rows($result) >= 1) {        
        while ($row = mysqli_fetch_array($result)) {
            echo "<a class=\"dropdown-item\" href=\"producten.php?id=" . $row['productnr'] . "\">" . $row['naam'] . "</a>\n";
        }
    }
    else {
        echo "<a class=\"dropdown-item\" href=\"#\">No results!</a>";
    }
}

0 个答案:

没有答案