Reputation: 370
When someone starts typing (number or alphabets), I want a search bar to appear and it should take the alphabets that are being written by the user in it, ie, I want it to automatically focus on the field.
So far I have this..
if (window.addEventListener) {
var keys = [], listen= /^([0-9]|[a-z])\i$/ ;
window.addEventListener("keydown", function(e){
keys.push(e.keyCode);
if(keys.match(listen))
{
$('#searchBar').fadeIn();
$('#searchBar input').text(keys);
$('#searchBar input').focus();
keys = [];
}
},true);
}
I want the first character that was typed in to show in the field too. Ty.
Upvotes: 0
Views: 1587
Reputation: 94
Hope this works for you. If you prefer jQuery, minor changes needs to be made.
<style>
#searchBar { display: none; }
.search { width: 250px; height: 20px; }
</style>
<div id="searchBar">
Search Here: <input type="search" id="searchInput" class="search" />
</div>
<script>
window.onload = function() {
var listen = /^[a-z0-9]+$/i;
var searchInput = document.getElementById('searchInput');
var searchBar = document.getElementById('searchBar');
if ( window.addEventListener )
window.addEventListener( 'keyup', insertKey, false);
function insertKey( e ) {
// Get the character from e.keyCode
var key = String.fromCharCode( e.keyCode ).toLowerCase();
// Match the character
if( key.match(listen) ) {
// Change display: none; to display: block;
searchBar.style.display = "block";
// Append every new character
searchInput.value += key;
// Focus on input
searchInput.focus();
// Since you focused on the input you don't need to listen for keyup anymore.
window.removeEventListener( 'keyup', insertKey );
// I didn't tested with jQuery
// $('#searchBar').fadeIn();
// $('#searchBar input').append(keys);
// $('#searchBar input').focus();
}
}
};
</script>
Upvotes: 1
Reputation: 49
var listen= /^([0-9]|[a-z])\i$/;
var key = [];
window.addEventListener('keydown', function (e) {
keys.push(e.keyCode);
if(keys.match(listen)) {
$('#searchBar').fadeIn();
$('#searchBar input').append(keys);
$('#searchBar input').focus();
keys = [];
}
});
Upvotes: 0