仅在<datalist>字段中输入3个字符后才显示自动完成功能?

时间:2019-07-25 13:01:57

标签: javascript

是否只有在用户输入至少3个字母后才能自动完成? 这是我当前的代码:

HTML / PHP:

<form name="form" class="form-container" method="post" onsubmit="return doValidate()" id="myForm2">

                    <label> <input placeholder="Organisator" id="name" list="users" name="mitarbeiter" required /> </label> 
                         <datalist id="users" class="dle" >
                            <?php
                                for ($i=0; $i<$counts; $i++) {
                                    echo '<option value="'.$AllData[$i]["mail"][0].'">'.$AllData[$i]["cn"][0].'</option>'; 
                                }
                            ?>
                         </datalist>
                    <br><br>
                    von <input type="time" name="zeitstart" class="zeitangaben" id="startzeitid"> Uhr bis <input type="time" name="zeitende" id="endzeitid" class="zeitangaben"> Uhr <br><br> 

            <button type="submit" class="btn" name="submit">Reservierung erstellen</button>
            <button type="reset" class="btn cancel" onclick="hideDiv()">Abbrechen</button>
        </form>

我只能在Jquery中找到一些代码,没有jquery就无法做到吗?

有可能吗?有什么想法吗?

3 个答案:

答案 0 :(得分:3)

您需要使用javascript并监听keyup事件作为输入元素。

然后您检查输入的值是否大于3个字符,如果大于3个字符,则需要向服务器发出ajax请求以获取相关名称并使用它们来填充datalist

答案 1 :(得分:1)

这是完整的自动完成示例。

首先,我添加了一个名为auto的输出,以便可以输出这些名称的命题。

<div id="auto"></div>

然后,我声明了这些变量。

// Selects the output.
var auto = document.querySelector("#auto");

// Selects the input.
var input = document.querySelector("#name");

// Selects all "datalist" children.
var options = document.querySelector("#users").children;

// The main auto complete proposition will go there.
var final_name;

现在,这是第一个addEventListener。在每个keyup上,它将检查字符数是否大于等于3。如果是,它将获取输入并将其与所有名称进行比较。然后,如果名称匹配,它将在显示名称的auto div中输出匹配的名称。

// Adds a keyup listener on the input.
input.addEventListener("keyup", (e) => {

    if (e.target.value.length >= 3) {

        // "cleans" the output zone so we can output new names.
        auto.innerHTML = "";

        var input_name = e.target.value.toLowerCase();

        // For each children (names) we check if the string matches the beggining of the name.
        for (var i = 0; i < options.length; i++) {

            var data_name = options[i].innerHTML;

            // Gets the last part of the name (ex: input = "ali", the last part would be "ci keys").
            var sliced_first = data_name.slice(0, input_name.length);

            // If the string matches the beggining of the name.
            if (sliced_first.toLowerCase() == input_name) {

                final_name = options[i].innerHTML
                auto.innerHTML += data_name + "<br>";
            }
        }
    }
});

第二个addEventListener监听keydown事件。如果按下tabulation键,它将在demo中提议的名称输出到input中。

// Adds a keydown listener on the input.
input.addEventListener("keydown", (e) => {

    // If "tab" key is pressed.
    if (e.keyCode == 9) {

        // Adds the name to the input.
        if (final_name) e.target.value = final_name;
    }
});

这是完整的代码。

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>reading json</title>
    <script type="text/javascript">function log(p) {return console.log(p)}</script>
</head>
<body>


<form name="form" class="form-container" method="post" onsubmit="return doValidate()" id="myForm2">

    <label><input placeholder="Organisator" id="name" list="users" name="mitarbeiter" required /></label> 
    <datalist id="users" class="dle">
        <option value="alicia@key.com">Alicia Keys</option>
        <option value="alicia@key.com">Alicia The Second</option>
        <option value="john@doe.com">John Doe</option>
        <option value="martin@scorsese.com">Martin Scorsese</option>
        <option value="iron@man.com">Iron Man</option>
    </datalist><br><br>

    <div id="auto"></div>

    <br><br>
    von <input type="time" name="zeitstart" class="zeitangaben" id="startzeitid"> Uhr bis <input type="time" name="zeitende" id="endzeitid" class="zeitangaben"> Uhr <br><br> 

<button type="submit" class="btn" name="submit">Reservierung erstellen</button>
<button type="reset" class="btn cancel" onclick="hideDiv()">Abbrechen</button>

</form>

<script>


// Selects the output.
var auto = document.querySelector("#auto");

// Selects the input.
var input = document.querySelector("#name");

// Selects all "datalist" children.
var options = document.querySelector("#users").children;

// The main auto complete proposition will go there.
var final_name;

// Adds a keyup listener on the input.
input.addEventListener("keyup", (e) => {

    if (e.target.value.length >= 3) {

        // "cleans" the output zone so we can output new names.
        auto.innerHTML = "";

        var input_name = e.target.value.toLowerCase();

        // For each children (names) we check if the string matches the beggining of the name.
        for (var i = 0; i < options.length; i++) {

            var data_name = options[i].innerHTML;

            // Gets the last part of the name (ex: input = "ali", the last part would be "ci keys").
            var sliced_first = data_name.slice(0, input_name.length);

            // If the string matches the beggining of the name.
            if (sliced_first.toLowerCase() == input_name) {

                final_name = options[i].innerHTML
                auto.innerHTML += data_name + "<br>";
            }
        }
    }
});

// Adds a keydown listener on the input.
input.addEventListener("keydown", (e) => {

    // If "tab" key is pressed.
    if (e.keyCode == 9) {

        // Adds the name to the input.
        if (final_name) e.target.value = final_name;
    }
});

// I had to include your doValidate() function otherwise I would get an error while validaing.
function doValidate() {};

</script>
</body>
</html>

我希望能有所帮助。片段:

// Selects the output.
var auto = document.querySelector("#auto");

// Selects the input.
var input = document.querySelector("#name");

// Selects all "datalist" children.
var options = document.querySelector("#users").children;

// The main auto complete proposition will go there.
var final_name;

// Adds a keyup listener on the input.
input.addEventListener("keyup", (e) => {

    if (e.target.value.length >= 3) {

        // "cleans" the output zone so we can output new names.
        auto.innerHTML = "";

        var input_name = e.target.value.toLowerCase();
        
        // For each children (names) we check if the string matches the beggining of the name.
        for (var i = 0; i < options.length; i++) {

            var data_name = options[i].innerHTML;

            // Gets the last part of the name (ex: input = "ali", the last part would be "ci keys").
            var sliced_first = data_name.slice(0, input_name.length);

            // If the string matches the beggining of the name.
            if (sliced_first.toLowerCase() == input_name) {

                final_name = options[i].innerHTML
                auto.innerHTML += data_name + "<br>";
            }
        }
    }
});

// Adds a keydown listener on the input.
input.addEventListener("keydown", (e) => {

    // If "tab" key is pressed.
    if (e.keyCode == 9) {

        // Adds the name to the input.
        if (final_name) e.target.value = final_name;
    }
});

// I had to include your doValidate() function otherwise I would get an error while validaing.
function doValidate() {};
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>reading json</title>
    <script type="text/javascript">function log(p) {return console.log(p)}</script>
</head>
<body>


<form name="form" class="form-container" method="post" onsubmit="return doValidate()" id="myForm2">

    <label><input placeholder="Organisator" id="name" list="users" name="mitarbeiter" required /></label> 
    <datalist id="users" class="dle" autocomplete="off">
        <option value="alicia@key.com">Alicia Keys</option>
        <option value="alicia@key.com">Alicia The Second</option>
        <option value="john@doe.com">John Doe</option>
        <option value="martin@scorsese.com">Martin Scorsese</option>
        <option value="iron@man.com">Iron Man</option>
    </datalist><br><br>

    <div id="auto"></div>
    
    <br><br>
    von <input type="time" name="zeitstart" class="zeitangaben" id="startzeitid"> Uhr bis <input type="time" name="zeitende" id="endzeitid" class="zeitangaben"> Uhr <br><br> 

<button type="submit" class="btn" name="submit">Reservierung erstellen</button>
<button type="reset" class="btn cancel" onclick="hideDiv()">Abbrechen</button>

</form>
</body>
</html>

答案 2 :(得分:0)

我只是想分享我在 setAttributeremoveAttribute 上使用 keyUpkeyDown 所做的事情来显示数据列表 (dir) 时文本框至少包含 3 个字符并处理退格键 (keyCode=8) 以防止在扩大搜索结果时显示完整列表。

<input type="search" name="q" id="q" autofocus="true"
       onkeyup="if(this.value.length>=3)this.setAttribute('list','dir');" 
       onkeydown="if(this.value.length<3||event.keyCode==8)this.removeAttribute('list');"
       placeholder="Search Staff Directory"
/>

希望这可以帮助任何正在寻找不需要 jQuery 或 Ajax 的简单解决方案的人,只需一个简单的数据列表。