开发者

jQueryUI autocomplete - place search results adjacent to input in DOM

I'm using jQueryUI's autocomplete, but for the following reasons I'd like to move the search results into the DOM next to the input tag that's doing the search.

It's easiest to see this on jsFiddle, but essentially code demonstrating the issue looks like so:

<html>    <head>
<link rel="stylesheet" type="text/css"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/flick/jquery-ui.css" /> 

<sc开发者_运维技巧ript src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript"> google.load("jquery", "1.4");
   google.load("jqueryui", "1.8");  </script>
<script>
$(function() {
    $("#X").autocomplete({
        source: ['abc', 'def', 'ghi']
    });
});
</script>
<style type="text/css">
   .B {   display: none;    }
   .A:hover .B { display: block;  }
</style>
</head>  <body>

Hello
<div class='A'>
select:
  <div class='B'>
    <input id='X' />
  </div>
</div>
World

</body>   </html>

The problem is that when one hovers their mouse over an autocomplete option the element containing the autocompleting input tag is no longer in 'mouseover'ed' and per the CSS rules the input tag disappears with its container. This is not the desired behaviour; I'd like to keep the input tag visible when highlighting the autocomplete selections.

I would hope and expect that it'd be possible to move the autocomplete elements to the DOM next to the input tag (i.e. x = $("#X"); x.append(x.autocomplete('widget'))), and therefore the CSS rules would keep the input and its parent visible. Alas, this doesn't work.

I'd be grateful for any thoughts on how to achieve this mixture of CSS and jQueryUI.

Thank you.

Brian


This seems like something that should be supported natively in jQuery UI! Anyway, here's something that I think will work:

$("#X").autocomplete({
    source: ['abc', 'def', 'ghi'],
    open: function($event, ui) {
        var $widget = $("ul.ui-autocomplete");
        var $input = $("#X");
        var position = $input.position();

        $("div.B").append($widget);

        $widget.css("left", position.left + $input.width());
        $widget.css("top", position.top);       
    }
});

This positions the widget by moving the auto-complete box to the right of the input, and solves the rollover problem by appending the widget to the same <div> the <input> belongs to.

http://jsfiddle.net/U2B9f/1/

Edit: This solution will work, especially for older versions of jQuery UI, but Brian's answer below is a better solution.


Here's an answer that could be preferable to Andrew Whitaker's (and per the ticket I started: http://bugs.jqueryui.com/ticket/6724):

Using the appendTo option of autocomplete, i.e.

$("#X").autocomplete({
  appendTo: $(".B"),
  source: ['abc', 'def', 'ghi'],
});

You can see this in action on jsFiddle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜