Отправить данные из текстового поля ИЛИ Jquery меню автозаполнения - PullRequest
0 голосов
/ 01 апреля 2020

У меня есть jquery меню автозаполнения для поиска книг. Автозаполнение работает нормально, но мне все равно хотелось бы выполнить поисковый запрос (данные POST) из текста, набранного в текстовом поле, нажав клавишу ввода и игнорируя предложения автозаполнения.

Я пытался jquery отправить форму, которая всегда отключает меню автозаполнения. Я не уверен, что делать.

Ниже приведен код, который у меня сейчас есть с автозаполнением, которое работает.

<!DOCTYPE html>
<html>
<head>

<!-- Your web-app is https, so your scripts need to be too -->

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/stylesheets/style.css" type="text/css">

<script type="text/javascript">

    function post(path, params, method ='post') {

        // The rest of this code assumes you are not using a library.
        // It can be made less wordy if you use one.
        const form = document.createElement('form');
        form.method = method;
        form.action = path;

        for (const key in params) {
            if (params.hasOwnProperty(key)) {
                const hiddenField = document.createElement('input');
                hiddenField.type = 'hidden';
                hiddenField.name = key;
                hiddenField.value = params[key];

                form.appendChild(hiddenField);
            }
        }

        document.body.appendChild(form);
        form.submit();
    }

    $(document).ready(function() {



        $("#findBook").autocomplete({

            minLength: 0,
            scroll: true,

            source: function (request, response) {



                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "https://www.googleapis.com/books/v1/volumes?q=" + request.term,


                    success: function (data) {

                        var transformed = data.items.map(function (book) {
                            return {
                                title: book.volumeInfo.title,
                                author: book.volumeInfo.authors,
                                image: book.volumeInfo.imageLinks.thumbnail
                            };
                        });


                        response(transformed.slice(0, 5));
                    }


                });


            },


            select: function(event, ui){

               //console.log(ui.title);


                event.preventDefault();

                var id = ui.item.title;

                $.ajax({
                    url: "/book_profile_b/" + id,
                    type: "POST",
                    dataType: 'html',
                    data: { id: id },
                    success: function(data){


                        post('/book_profile_b/'+id);


                    },
                    error: function (xhr, ajaxOptions, thrownError) {

                        console.log(xhr.responseText+" - "+thrownError)
                        alert("ERROR:" + xhr.responseText+" - "+thrownError);
                    }
                });



            },


        }).autocomplete("instance")._renderItem = function (ul, item) {
            return $("<li></li>")

                .data("item.autocomplete", item)
                .append("<a><img class= 'imageClass' src='" + item.image + "' />" + item.title +  " " + "<div class=searchInfo>" +  "by" + " " + item.author + "</div>" + "</a>")
                .appendTo(ul)
                .append('<li><a href="/book_profile/b/'+ this.term + '">Search: '+ this.term + '</a></li>' );



           };

        });

</script>





<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="/style.css" type="text/css">
<link rel="stylesheet" href="/home.css" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Alegreya+Sans|EB+Garamond|Encode+Sans+Expanded|Inconsolata|Karla|Manuale|Nunito+Sans|Pontano+Sans|Roboto+Slab:300|Rokkitt|Sanchez" rel="stylesheet">
</head>
<body>






<div class="searchBook">


    <input type="text" placeholder="Search.." id="findBook" />


</div>





</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...