3
votes

I'm implementing a "auto suggestion feature". This means:

  • input element gets focus -> display suggestions
  • input element looses focus -> hide suggestions

But if the user want to select an option via mouse, the click event is not firing because the blur event fires earlier and hides the clickable element.

Here is the fiddle: http://jsfiddle.net/km8c0ft1/

Here is some example code: js:

$('#test').blur(function() {
    $('#dropdown').css("display", "none");
});
$('#test').focus(function() {
    $('#dropdown').css("display", "inline");
});

html:

<input id="test" />
<input />
<input />

<ul id="dropdown" style="display: none">
    <li><a onclick="alert('option 1 selected')">option 1</a></li>
    <li><a onclick="alert('option 2 selected')">option 2</a></li>
    <li><a onclick="alert('option 3 selected')">option 3</a></li>
</ul>

I understand the problem. But what is the best practice to solve this Problem? I can implement the setTimeout Function to wait some ms until i hide the menu. But this feels like a hack and not like a clean solution.

1
this is just a example to show the problem. The hole feature is highly integrated and non of the existing plugins works for me.user3796786

1 Answers

3
votes

Try this : You can use show() or hide() instead of changing css values. Bind click event for anchor inside li to set selected value to text box. Bind click event for document and check if target is not input box to hide options.

$('#dropdown li a').click(function(e) {
    $('#test').val($(this).text());
    $('#dropdown').hide();
});

$(document).on("focus click keydown blur","*",function(e){
    var keyCode = e.keyCode || e.which; 
    if(keyCode == 9 || e.target.id!='test')
    $('#dropdown').hide();
});

$('#test').on("focus click",function(e) {
    $('#dropdown').show();
});

DEMO with Single Input
DEMO with Multiple Input