0

I'm trying to achieve No results as a output after clearing the search-field through jQuery. But jQuery never detects when the input seach-field is empty.

Here is the 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>

EDIT: Needed 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>

And 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>";
    }
}
Alex
  • 322
  • 4
  • 18

0 Answers0