The solutions above are great, but if the user naturally just clicks next to the placeholder value, inside the input box, intending to keep and continue it, it will become completely erased.
So based on the solutions above, I did the following solution for me:
HTML:
<input id="other" list="values" value="<?php echo $val; ?>">
<datalist id="values">
<option value="orange">
<option value="banana">
</datalist>
JS:
jQuery(document).ready(function ($) {
function putValueBackFromPlaceholder() {
var $this = $('#other');
if ($this.val() === '') {
$this.val($this.attr('placeholder'));
$this.attr('placeholder','');
}
}
$('#other')
.on('click', function(e) {
var $this = $(this);
var inpLeft = $this.offset().left;
var inpWidth = $this.width();
var clickedLeft = e.clientX;
var clickedInInpLeft = clickedLeft - inpLeft;
var arrowBtnWidth = 12;
if ((inpWidth - clickedInInpLeft) < arrowBtnWidth ) {
$this.attr('placeholder',$this.val());
$this.val('');
}
else {
putValueBackFromPlaceholder();
}
})
.on('mouseleave', putValueBackFromPlaceholder);
});
For me there're many input boxes on the page, and I want only this one to have this behavior, so I work with id and have it "personal." If you wish to change it to the more generic function, you'll have to bind putValueBackFromPlaceholder
with the element, on which the click happened, and the event itself.