jQuery UI Autocomplete执行按钮点击问题搜索

时间:2017-09-28 21:52:46

标签: jquery-ui

我有一个工作UI自动完成jQuery。我想改变它的工作方式。用户从列表中选择一个值而不是新的浏览器选项卡,我希望用户首先选择一个值,然后单击搜索按钮来触发事件。

它可以工作但是如果你执行搜索然后再进行第二次搜索,它将同时触发先前的URL和新的URL。此外,如果您执行搜索,则单击搜索按钮而不在搜索输入中键入任何内容,从而触发上一次搜索。奇怪吧?我将添加我的代码,但我认为一个codepen示例将有助于澄清我的意思。

我遇到的另一个问题是,如果键入的值不在数组中,我正在尝试设置自定义警报,但无论输入什么,我都会收到无效的错误消息。我在代码中也添加了它。这是if语句之一。

JS

var mySource = [
   {
       value: "Google",
       url: "http://www.google.com"
   },
   {
       value: "Yahoo",
       url: "https://www.yahoo.com"
   },
   {
       value: "Hotmail",
       url: "https://hotmail.com"
   },
   {
       value: "Reddit",
       url: "https://www.reddit.com"
   }
];

//Logic for ui-autocomplete
$(document).ready(function() {
    $("input.autocomplete").autocomplete({
        minLength: 2,
        source: function(req, resp) {
            var q = req.term;
            var myResponse = [];
            $.each(mySource, function(key, item) {
                if (item.value.toLowerCase().indexOf(q) === 0) {
                    myResponse.push(item);
                }
                if (item.value.toUpperCase().indexOf(q) === 0) {
                    myResponse.push(item);
                }
                //Add if statement here to determine if what the user inputs is in the 
                // array
                //and if not in the array give an error to #textAlert.
                //Example
                if (item.value.indexOf(q) != myResponse) {
                    $('#alertText').text("Invalid Search");
                } else {
                    return false;
                }
            });
            resp(myResponse);
        },
        select: function(event, ui) {
            $('#appSearchBtn').one("click", function() {
                window.open(ui.item.url);
                $('#appsearch').val('');
               return false;
            });
        }
    });
});

//Input and ui text clears when clicked into
$(document).ready(function() {
    var input = document.querySelector('#appsearch');
    var ui = document.querySelector(".ui-helper-hidden-accessible");
    input.onclick = function() {
        input.value = '';
        ui.textContent = '';
    };
});

HTML

<p id="alertText"></p>
<div class="input-group">
    <input type="text" id="appsearch" class="form-control autocomplete" placeholder="Application Search" />
    <span class="input-group-btn">
        <button class="btn btn-primary inputBtn" id="appSearchBtn" type="button">Search</button>
    </span>
</div>

以下是代码笔https://codepen.io/FrontN_Dev/pen/MEmMRz,因此您可以看到它是如何工作的。我还添加了它应该如何工作以及错误是什么。

9/29/17 @ 0732 我解决了这个问题,事件一遍又一遍地触发相同的URL,但我仍然需要帮助,即使值在数组中,每次搜索都会出现自定义的无效搜索消息。

0 个答案:

没有答案
相关问题