2

I have a text field where the user is supposed to enter a city. The cities are in the form of a datalist selected from my databse. However, I don't want the user to be able to click the little arrow and see a dropdown of all the cities. I only want the cities to show once the user has started typing.

I looked around online and only found a solution to hide the arrow, without disabling it; i.e. if you click where the arrow should be, there is still a dropdown.

Is there anyway to disable this feature altogether?

4

2 回答 2

2

input您可以在收到点击时添加一个事件并暂时删除该list属性。然后就keydown你恢复属性了。

document.getElementById('myInput').addEventListener('click', function(e) {
    var input = e.target,
        list = input.getAttribute('list');
    
    if(list) {
        input.setAttribute('data-list', list);
        input.removeAttribute('list');
    }
});

document.getElementById('myInput').addEventListener('keydown', function(e) {
    var input = e.target,
        list = input.getAttribute('data-list');

    if(list) {
        input.setAttribute('list', list);
        input.removeAttribute('data-list');
    }
});
<input id="myInput" type="text" list="data">
<datalist id="data">
    <option>10</option>
    <option>12</option>
    <option>13</option>
</datalist>

于 2015-05-01T13:40:00.217 回答
0

Removing the list using Jquery/Javascript is an option.

<input type="text" onkeyup="setData()" id="test"/>

When user starts typing, have a keyup event and you could check if the length is greater than 1.If so, you can attach the attribute to the input element.

function setData() {        
    var data = $("#test").val();
    if (data.length > 1) {
       $("#test").attr('list', 'listname');     //This will add attribute to the input
    } else {
       $("#test").removeAttr('list');         //This will remove the attribute from the input
    }
}
于 2019-02-07T02:02:23.103 回答