1

For an autosuggest

i have one div for the input tag and another for the suggestions div...i want the suggestions div to disappear after either

1) an element is selected in the suggestions div

or

2) when an area outside the two divs is clicked

The question is where to add an "onblur" event right now i have

<input type = "text" name= "target" value = "" id="target" style="width:150px" onblur ="setTimeout('removeSuggestions()', 20);" onkeyup ="getSuggestions(this.value);"/>

<div id ="suggestions"></div>

and

function getSuggestions(value){
   if (value !=""){
   $.post("target.php", {targPart:value}, function(data) {
     $("#suggestions").html(data);
    if(value.length>2){
        doCSS();
        }

   });
   } else {
    removeSuggestions();
    }

  }

   function removeSuggestions(){

   $("#suggestions").html("");
   undoCSS();
   }
  function addText(value){

      $("#target").val(value);

  }
  function doCSS(){
  $("#suggestions").css({
      'border' : 'solid',
       'border-width': '1px'

    });

  }

  function undoCSS(){
   $("#suggestions").css({
      'border' : '',
       'border-width': ''

    });
  }

But everytime I try to click a suggestion the suggestions div goes away because once i go out of the input field remove suggestions is called. The timeout is supposed to help but isn't. How can i fix this?

algorithmicCoder
  • 6,595
  • 20
  • 68
  • 117

1 Answers1

1

Perhaps something like this will solve your problem. We only need to monitor the blur of search box because clicking out of it (even on suggestions) will trigger the hide event.

http://jsfiddle.net/9Yt9L/3/

$('#search').focus(function() {
    $('#suggestions').slideDown();
});

$('#search').blur(function() {
    $('#suggestions').slideUp();
});

$('#suggestions div').click( function() {
    $('#search').val($(this).html());
});
mrtsherman
  • 39,342
  • 23
  • 87
  • 111
  • but why would what i did not work?...what "problem" with my approach does this solve?... – algorithmicCoder Oct 07 '11 at 06:18
  • I suppose it would work, but you have a timeout of 20 milliseconds. Way too short to notice. Its a bad way of doing things in my opinion. Tough to troubleshoot and prone to breakage. – mrtsherman Oct 07 '11 at 13:32