javascript - 是否可以根据您输入的内容进行文本输入和建议?

标签 javascript html forms input dropdown

如何根据我在文本字段中输入的内容显示下拉列表,其中所选选项会将其自身“写入”到文本字段中?例如,如果我被问到我最喜欢的颜色是什么,我首先输入“dar”,则会出现一个下拉菜单,其中包含选项“深红色”、“深蓝色”、“深绿色”等。但是,如果我输入“深 g”会出现一个只有选项“深绿色”的下拉菜单?可以把它想象成一个文本输入,它消除了下拉列表中的选择,但是在下拉列表中选择一个选项会将它们输入到文本字段中。

这是我目前的代码(尽管我认为我需要 JS?):

<input type="text" placeholder="Name Of Gear">
                <input type="number" class="amount" maxlength="4" placeholder="Amount" max="999">

最佳答案

如果你想自动补全整个字典,这会很慢。 但如果您只想自动完成一些单词(如“绿色”、“红色”等),这应该可以做到。

在您的 HMTL 中,您需要一个输入和一个 div。 输入用于打字,div 提供建议。

<input id="input" oninput="findSuggestions('input', 'suggestions')">
<div id="suggestions"></div>

因此,如果您键入,就会调用一个函数。 该函数将遍历一个包含所有建议的数组。

var arySuggestions = ["Alarm", "Already" , "Ballon"] // This is where all you suggestions go

function findSuggestions(strInputId, strSuggestionsDivId) { 
    var objInput = document.getElementById(strInputId)
    var strInput = objInput.value // get the current text

    var objSuggestionsDiv = document.getElementById(strSuggestionsDivId)

    if (strInput.length > 0) {
        objSuggestionsDiv.innerHTML = ""; // empty the suggestion div, just in case
        var objList = document.createElement("ul");

        for (var i = 0; i < arySuggestions.length; i++) {
            var word = arySuggestions[i]
            var wordPart = word.substring(0,strInput.length)
            if (word.length > strInput.length && wordPart === strInput) { // check if the words are matching
                // if they do create a list entry
                var objListEntity = document.createElement("li");
                objListEntity.setAttribute("onclick", "complete('" + word + "', '" + strInputId + "', '" + strSuggestionsDivId + "');");
                objListEntity.innerHTML = word;
                objList.appendChild(objListEntity);
            }
        }
        // show the suggestionList
        objSuggestionsDiv.appendChild(objList);
    } else {
        objSuggestionsDiv.innerHTML = ""; // empty the suggestion div
    }
}

还有第二个功能。这样,当您单击建议时,它就会填写:

function complete(strComplete, strInputId, strSuggestionsDivId) {
    document.getElementById(strInputId).value = strComplete;
    document.getElementById(strSuggestionsDivId).innerHTML = ""; // empty the suggestion div
}

如果您希望建议跟随光标,您可能需要一些 css。

希望这有帮助

关于javascript - 是否可以根据您输入的内容进行文本输入和建议?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47611326/

相关文章:

Javascript 二分查找/插入性能

javascript - 将用户重定向到 Windows 8 中的桌面浏览器

html - CSS class1 > class2 是什么意思?

javascript - 默认选中按钮

javascript - 对触发调用的表单的 jQuery 引用

CSS 菜单在 IE7 或更低版本中不起作用

ruby-on-rails - 为什么我要获取表单时,form_tag方法是帖子?

javascript - 带有表单值的 jQuery AJAX 提交

javascript - 使用动态模板对 Angular Directive(指令)进行单元测试

html - CSS : Sub Class is not working