简体   繁体   中英

How to assign datalist to input?

I have this HTML:

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

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

and this 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. 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:

<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.

You need to set attribute of the element use .attr(attributeName, value) and .removeAttr(attributeName)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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