1

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.

Tom
  • 2,962
  • 3
  • 39
  • 69

1 Answers1

2

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')
    }
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • But what is the difference between $(this).attr('list') and this.list? NVM found out here: http://stackoverflow.com/questions/8426461/javascript-setattribute-v-s-element-attribute-value-to-set-name-attribut – Tom May 20 '16 at 12:59
  • 1
    @Tom, `this.list` means you are fetching the property of `this` object. and input doesn't have a `list` property – Satpal May 20 '16 at 13:05