简体   繁体   English

如何为输入分配数据列表?

[英]How to assign datalist to input?

I have this HTML: 我有这个HTML:

<input type="text" name="city" autocomplete="off">

<datalist id="seek_list">
<option value="Value1">
<option value="Value2">
</datalist>

and this Javascript: 和这个Javascript:

$('input[name=city]').on('keyup', function()
{
    if (this.value.length > 1)
    {
        this.list = 'seek_list';
    }
    else
    {
        this.list = ''; 
    }
});

I want the autocomplete to work after user types 2 or more chars in the input field, but this doesn't work. 我希望自动填充功能在用户在输入字段中输入2个或更多字符后起作用,但这不起作用。 The datalist is not assigned. 数据列表未分配。 I also tried this approach but with no luck: 我也尝试过这种方法,但是没有运气:

<input type="text" name="city" autocomplete="off" list="seek_list">

<datalist>
<option value="Value1">
<option value="Value2">
</datalist>

$('input[name=city]').on('keyup', function()
{
    if (this.value.length > 1)
    {
        $('datalist')[0].id = "seek_list";
    }
    else
    {
        $('datalist')[0].id = "";
    }
});

The only thing that worked was an empty datalist with this HTML: 唯一起作用的是此HTML的数据列表为空:

<input type="text" name="city" autocomplete="off" list="seek_list">

<datalist id="seek_list">
</datalist>

and appending options to the datalist with Javascript, but that was slow. 并使用Javascript将选项附加到数据列表,但这很慢。

You need to set attribute of the element use .attr(attributeName, value) and .removeAttr(attributeName) 您需要使用.attr(attributeName, value).removeAttr(attributeName)设置元素的.removeAttr(attributeName)

$('input[name=city]').on('keyup', function() {
    if (this.value.length > 1) {
        $(this).attr('list', 'seek_list');
    } else {
        $(this).removeAttr('list')
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM