I'm trying to get some sort of suggestion box in my application. The basic idea is that, when typing in an input box, 5 options show up below the input box with possible entries.
The problem I am facing is that, while there is nothing entered in the input box, the box which gives the possible suggestions already shows (see Screenshot). Of course, I only want it to show up when I enter something in the input box.
Any help?
Wout
CSS-code:
#suggestions {
-moz-box-sizing: border-box;
box-sizing: border-box;
border: 1px solid black;
position: absolute;
left: 310px;
top: 5px;
background-color: white;
font-size: 12px;
}
JavaScript: --> option1, option2,... get a value in function "giveSuggestion()"
<form id = "suggestions">
<input type = "text"
id = "insertText"
autocomplete="off"
onkeyup = "if (event.keyCode == 13) {SearchAddress(option1.text)}
else {giveSuggestion()}"/>
<option id = "option1" onclick = "searchAddress(option1.text)"></option>
<option id = "option2" onclick = "searchAddress(option2.text)"></option>
<option id = "option3" onclick = "searchAddress(option3.text)"></option>
<option id = "option4" onclick = "searchAddress(option4.text)"></option>
<option id = "option5" onclick = "searchAddress(option5.text)"></option>
</form>
There is a standard way of doing that. HTML5 <datalist> tag! And the global browser support for it 74.5%. You may use the above fiddle as a fallback support. Watch this
Check this out: https://jsfiddle.net/gnph4evm/1/
I have added a new class:
.option{
display:none;
}
and added it to all your options like:
<option class="option" id = "option1" onmousedown = "searchAddress(option1.text)" >text1</option>
added functions for toggling the visibility:
showOptions = function (){
$('.option').show();
}
hideOptions = function (){
$('.option').hide();
}
and for the grand finale, added onfocus and onfocusout calling thoose functions
<input type = "text"
id = "insertText"
autocomplete="off"
onkeyup = "if (event.keyCode == 13) {SearchAddress(option1.text)}
else {giveSuggestion()}" onfocus='showOptions()' onfocusout='hideOptions()'/>
Hope it's helpful
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With