Live search suggestions

319 Views Asked by At

I used ajax to create a live search connected to the database(site e-commerce). when there is a value in the input several suggestions are fetched in the screen . I want to take the id when the client click in a suggestion. The suggestions cant be clickable i dont know why!! here is my jquery code :

    $('.clicked').click(function() {
        console.log($("#input_value").val());
        
    });

    var x;
    var value = $("#input_value").val();
    $('.clicked').click(function() {
    $.ajax({
        type:'GET',
    //     // url: 'test.php?name=' + $("#testo").val(),
        data: { name : value },
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        success: function()
        {
            window.location.href = 'un_produit.php?id=' + $("#input_value").val();
        
        }
    });

I tried to add the class to a div and it works when i click but it doesnt work with the suggestions of the live search .

2

There are 2 best solutions below

1
Webdeveloper_Jelle On

Instead of using an AJAX request you could use JQUERY autocomplete.
This is an easy example on how this works, your URL source should return the data in this format:

 [{"label": "item 1", "value": "0"}, {"label": "item 2", "value": "2"}, {"label": "item 3", "value": "3"}]

I used this url as reference: https://www.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/

$(function() {
        $("#autocomplete").autocomplete({
            source: [{"label": "item 1", "value": "0"}, {"label": "item 2", "value": "2"}, {"label": "item 3", "value": "3"}], // this can be an url as well
            select: function( event, ui ) {
                var label = ui.item.label;
                if (label === "no results") {
                    // this prevents "no results" from being selected
                    event.preventDefault();
                }
                else {

                    /* do something with the selected result */
                    $("#autocomplete").val(ui.item.label);
                    event.preventDefault();
                    // or get the id
                     $("#autocomplete").val(ui.item.value);

                }

            }
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- jQuery UI library -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>

<input type="text" id="autocomplete">

0
AudioBubble On

The problem is solved, I had to add the class="clicked" into the the child element of the suggestion div and not to the div itself. thank you