0

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.

2
  • Did you try to write something? Is there a specific reason you build your own and not use some lib for that? jquery-ui for example, combined with regular input Commented Jul 25, 2016 at 0:02
  • I might look into the jquery-ui for this. Thank you. And I am trying to use input field as a part of the selection function. Commented Jul 25, 2016 at 0:07

1 Answer 1

1

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!!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.