Customize input type=”text” datalist to show only last 10 saved values

0
man people woman hand

Photo by RealToughCandy.com on Pexels.com

When there is a long list of values in the datalist, they will all get displayed with a scroll bar.


Requirement
Apply limit to html textbox datalist to display only x-amount of options. In other words, show last 10 saved values on textbox click but search through the whole list as the user begins typing in the input.


Textbox click
input type text show x number of items
Searching through the list

Search through all options on typing


<div>
Please select: <input type="text" id="Text1" list="A">
</div>

<datalist id="A">
<option value="None">
<option value="1">
<option value="2">
<option value="3">
<option value="4">
<option value="5">
<option value="6">
<option value="11">
<option value="22">
<option value="33">
<option value="44">
<option value="55">
<option value="66">
</datalist>

<datalist id="B">
<option value="66">
<option value="55">
<option value="44">
<option value="33">
<option value="22">
</datalist>

Solution
Since list does not provide much options. Trick is to have two data lists and swap on keyup and mousedown

<script>
var search = document.getElementById('Text1');
search.addEventListener('keyup', function handler(event) {
    document.getElementById('Text1').setAttribute('list', "A");
});

search.addEventListener('mousedown', function handler(event) {
    document.getElementById('Text1').setAttribute('list', "B");
});
</script>


Get Free Email Updates!

Signup now and receive free offers, discounts & coupon codes

I agree to have my personal information transfered to Mad Mimi ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.

Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge

This site uses Akismet to reduce spam. Learn how your comment data is processed.