There are a few solutions out there to display all the options in a datalist dropdown when a value is set and the down arrow is clicked. But none of them dealt with the case when a placeholder was already set initially.
I have therefore adapted a solution so that the initial placeholder is restored.
How it works:
- Down arrow clicked: Set a placeholder with the input value and clear the input value
- On mouseenter event: Save the original/initial placeholder value
- On mouseleave event: Restore the input value and restore the initial
placeholder, if the input value is blank.
My question is, if you see any flaws or unhandled cases in this code.
https://jsfiddle.net/Smolo/1y9mne2o/
function dlRestoreValue(i) {
let t = $('#' + i);
if (t.val() === '') {
if (t.attr('org-placeholder') !== t.attr('placeholder')) {
t.val(t.attr('placeholder'));
}
t.attr('placeholder', '');
if (t.val() === '') {
t.attr('placeholder', t.attr('org-placeholder'));
}
}
}
function dlShowAllOnArrowClick(i) {
$('#' + i)
.on('click', function(e) {
let t = $(this);
if ((t.width() - (e.clientX - t.offset().left)) < 14) {
if (t.val() !== "") {
t.attr('placeholder', t.val());
t.val('');
}
} else {
dlRestoreValue(i)
}
})
.on('mouseleave', function() {
dlRestoreValue(this.id);
})
.on('mouseenter', function() {
if (!$(this).is("[org-placeholder]")) $(this).attr('org-placeholder', $(this).attr('placeholder'));
})
}
dlShowAllOnArrowClick('favcolors');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Favorite color:
<input type="text" id="favcolors" list="colors" placeholder="Pick a color">
<datalist id="colors">
<option value="Blue">
<option value="Brown">
<option value="Cyan">
<option value="Green">
<option value="Orange">
<option value="Pink">
<option value="Purple">
<option value="Red">
<option value="Yellow">
</datalist>