tags:

views:

904

answers:

4

I am trying to use an Ajax search\suggest box. I use jQuery to handle the textbox losing focus. However, when I click on a link in the suggestion list jQuery fires the blur event and the link is not followed. Here is the jQuery code:

$(document).ready(function() {

    $('#lstxt').click(function() {
        this.value = '';
    });
    $('#lstxt').blur(function() {
        this.value = 'Database Search';
        document.getElementById('ls').innerHTML='';
        document.getElementById('ls').style.border='0px';
    });
});

How do I get it to not fire .blur if a link is being clicked inside the suggestion list (id="ls_table")?

A: 

try this code:

$(document).ready(function() {

    $('#lstxt').click(function() {
        this.value = '';
        return true;
    });
    $('#lstxt').blur(function() {
        this.value = 'Database Search';
        $('#ls').html('').css('border',"0px");
        return true;
    });
});

edit: blur will fire if you click outside of a textbox. is lstxt a textbox?

edit2: you will need to unbind the blur event and rebind it conditionally. i would need more info about your page layout to tell you how to do it

mkoryak
+1  A: 
var global_switch = false;
$('#ls_table').hover (
  function () { global_switch = true; },
  function () { global_switch = false; }
)
$('#lstxt').blur(function() {
  if (global_switch) { return; } else { ...});

This is just a proof of concept. As always, global variables are bad. Take a look at jQuery's data API to circumvent it.

Cheers,

Boldewyn
that's a good suggestion that we used, +1 ;)
Bozho
A: 

Not an answer - I am the original poster.

I tried your suggestion Boldewyn, but no change (except that the url of the link remained in the status bar of the browser).

Here is the relevant page layout:

<div class='ls_span'>
    <input type='text' name='lstxt' id='lstxt' class='ls_textbox' size='30' onkeyup='showResult(this.value)' value='Database Search'>
  <image src='../images/search1.gif' alt='Database Search' height='18' width='18'>
    </div>

    <div id='ls'></div>

The 'ls_table' element is created dynamically and inserted into the 'ls' div (showResult is an httprequest to a php script).

menkes
A: 

The method I used when implementing my own is adding a slight delay:

$('#lstxt').blur(function(){
    setTimeout(function(){
        // original blur code here
    }, 250);
});

Definitely not the best solution (but usually works). But Boldewyn's solution should work -- assuming that #ls_table has been created before trying to assign it. If you're creating/destroying #ls_table frequently, you can bind the event to the parent element:

// just using the data API for jquery.
$('#ls').hover(
    function(){ $('#ls').data('autocompleteover', 1); },
    function(){ $('#ls').data('autocompleteover', 0); }
);
$('#lstxt').blur(function(){
    if($('#ls').data('autocompleteover'))
        return;
    // original blur code here
}
Jeff