steve Kim steve Kim - 4 months ago 10
jQuery Question

JS: input field and dropdown option change

I am building my own dropdown options with input field as below:

<input class="search" type="text">
<div class="dropdown">
<div class="option" data-options="1">1</div>
<div class="option" data-options="2">2</div>
<div class="option" data-options="3">3</div>
<div class="option" data-options="4">4</div>
<div class="option" data-options="5">5</div>
</div>


enter image description here

I am little baffled with two functions:

1. When you are in the "input" field, I want to be able to use arrow keyboard button (down or up button) to select one of the options (option css change like
.option:hover{background:black; color:white;}
and 2. show in the input field as you press the arrow button on the keyboard.

Any suggestions will be much appreciated.

Thank you.

Answer

Please check if it's ok click into the input and use key arrow up and down for navigate.

$(document).ready(function(){
	window.displayBoxIndex = -1;

	$("#search").keyup(function(e) {
		if (e.keyCode == 40) {  Navigate(1); }
		if(e.keyCode==38) { Navigate(-1); }
	});
                   
	var Navigate = function(diff) {
		$('#search').val('');
		displayBoxIndex += diff;
		var oBoxCollection = $(".option");
		if (displayBoxIndex >= oBoxCollection.length) {
			displayBoxIndex = 0;			
		}
		if (displayBoxIndex < 0) {
			displayBoxIndex = oBoxCollection.length - 1;
		}
		var cssClass = "option_box_hover";
		oBoxCollection.removeClass(cssClass).eq(displayBoxIndex).addClass(cssClass);
		var optionsel = $(".option_box_hover").attr('data-options');
		$('#search').val(optionsel);
	}
	

});
.option_box_hover, .option_box:hover
{
  background:black;
  color:#FFFFFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<input id="search" class="search" type="text">
<div class="dropdown">
  <div class="option" data-options="1">1</div>
  <div class="option" data-options="2">2</div>
  <div class="option" data-options="3">3</div>
  <div class="option" data-options="4">4</div>
  <div class="option" data-options="5">5</div>
</div>

cheers!!