JSFiddle - React, Tailwind, and code Playground
HTML
<div id="search-container">
<input type="text" name="search" id="search" />
<input type="text" disabled="disabled" id="suggestion" />
</div>
CSS
* { margin: 0; padding: 0; }
#search-container {
position: relative;
}
#search-container input {
padding: 5px;
font-size: 1.2em;
width: 200px;
}
#search {
position: relative;
color: #000;
z-index: 10;
border: 1px solid #666;
background: transparent;
}
#suggestion {
position: absolute;
top: 0;
left: 0;
z-index: 0;
color: #ccc;
background: transparent;
border: 1px solid #fff;
}
JavaScript
$(function() {
var haystack = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$('#search').keyup(function(e) {
// 'enter' key was pressed
var $suggest = $('#suggestion');
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
$(this).val($suggest.val());
$suggest.val("");
return false;
}
// some other key was pressed
var needle = $(this).val();
// is the field empty?
if (!$.trim(needle).length) {
$suggest.val("");
return false;
}
// compare input with haystack
$.each(haystack, function(i, term) {
var regex = new RegExp('^' + needle, 'i');
if (regex.test(term)) {
$suggest.val(needle + term.slice(needle.length));
// use first result
return false;
}
$suggest.val("");
});
});
});