MedMatrix
MedMatrix

Reputation: 336

How to show autocomplete results in a specific div

I have an autocomplete field into my website. I just want to display the results inside a <div> tag instead the popup window that the plugin opens natively.

I searched already for solutions for this in other posts, but what they do is to change the position of the "popup" window, and what I want is to replace the content of the <div> with the results, not to put the popup over it.

This is my code :

$('#keyword').autocomplete(
{
    source : '/Dev/pages/suivi_searchCompany.php',
    select: function( event, ui )
    {               
        console.log(ui.item.value);
        loadHisto(ui.item.value);
        loadInfosCompanies(ui.item.value);
        loadInfosContact(ui.item.value)    
    }   
})
.data( "ui-autocomplete" )._renderItem = function( ul, item )
{
    console.log('test');
    console.log(item);
    console.log(ul);
    return $( "<li>" )
        .append( "<a>" + item.name + "</a>" )
        .appendTo( ul ); 
};

Upvotes: 0

Views: 2984

Answers (1)

WcPc
WcPc

Reputation: 457

An ugly but maybe sufficient solution might be to simply copy the content of the jquery-ui-generated div to your div and hide the default div:

jQuery:

$('#ui-id-1').bind('DOMSubtreeModified', function() {
  $('#mycontainer').html($('#ui-id-1').html());
});

Empty custom div if input is empty:

$('#keyword').keyup(function() {
    if($(this).val() == '') {
    $('#mycontainer').html('');
  }
});

CSS:

#ui-id-1 {
  display: none !IMPORTANT;
}

JSFiddle

The ID of the default autocomplete div (#ui-id-1) might vary.

UPDATE:

To add one of the possible options from the dropdown to your textbox, add this:

$('#mycontainer').on('click', 'li', function() {

  //add option to textbox
  $('#keyword').val($(this).html());

  //hide / clear dropdown
  $('#mycontainer').html('');
});

See updated fiddle (which I tidied up a bit aswell).

Upvotes: 1

Related Questions