0

I'm looking for some help in customizing the dropdown that displays the results of autocomplete. I have the following html which I want to use to display the results. The idea is that the div below is hidden to begin with and as soon there is a match, I make the div visible and each matched results would be wrapped in the < li > tag below.

<div class="search_dropdown_wrapper" style="display:none;">
    <div id="search_arrow" class="dropdown_pointer search"></div>
    <ul>
        <li>
            <img src="/assets/2c42cdf.jpg"  />
            <h4>Tom Jerry</h4>
            <p>Cartoon Characters</p>
        </li>
        <li>
            ...
        </li>
        ...  
    </ul>
</div>

The portion of my autocomplete code which works to display the results is..

  $('#search_name').autocomplete({
    minLength: 2,
    ...
    ...
  })
  .data( "autocomplete" )._renderItem = function( ul, item ) {
      return $( "<li></li>" )
      .data( "item.autocomplete", item )
      .append( "<a>" + item.name + "</a>" )
      .appendTo( ul );
  };

(FYI, the above thanks to How to set-up jquery-ui autocomplete in Rails)

At the moment I only have the name (item.name) displaying in the dropdown. How can I get the html I want into the code above. The part where I'm confused is how to get the div around the ul item which is being passed into the function. Thanks.

Community
  • 1
  • 1
absolutskyy
  • 567
  • 10
  • 20

2 Answers2

0

Use .parent() to get to the div around the ul: http://api.jquery.com/prev/

$(ul).parent()

Or, to grab the previous sibling: (as I somehow though you needed to do at first) http://api.jquery.com/prev/

$(ul).prev()

If ul is already a jQuery object, then you can just do ul.parent() and ul.prev()

Alternatively, you can access the wrapper div directly:

$('.search_dropdown_wrapper')

I might suggest adding an ID to that wrapper and accessing it by ID, eg:

<div class="search_dropdown_wrapper" id="search_dropdown_wrapper">
...
</div>

Then in your script you can use $('#search_dropdown_wrapper') to access the div directly.

The direct access approach is safer. If you ever change your markup, it will still access the correct div (theoretically.)

Thom Porter
  • 2,604
  • 2
  • 19
  • 23
  • Thanks, I prefer the direct approach too. I can do something like .appendTo($('#search_dropdown_wrapper ul')); which works and the
  • is inserted into the ul; but since the $('.search_dropdown_wrapper') is hidden by default, how and where do I insert the code to make it visible? Having a hard time with that.
  • – absolutskyy Oct 11 '12 at 07:03