0

I have a field #autoc1 which is used for autocomplete.

All works great but I want to add an item to the end of the generated UL to allow a user to add a new item should the autocomplete not find what they look for.

My thinking is to append the generated UL on focus in the text input so the option is always there

I'm trying the following but not working:

$(function() {
            $( "#autoc1" ).autocomplete({
                source: "/pages/includes/getAgent.php",
                minLength: 2,
                select: function( event, ui ) {
                    $('#autoc1').val(ui.item.agent_name);
                    $('#comm').val(ui.item.commission_percent);
                    return false;
                }
            }).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
                return $( "<li>" )
                .append( "<a>" + item.agent_name + "</a>" )
                .appendTo( ul )
            };

            $('#autoc1').focus(function() {
                $('#ui-id-1').append('<li><a href="new.html">Add new</a></li>');
            });
});

This is auto generated html

<ul style="display: none; width: 360px; top: 248px; left: 856.5px;" tabindex="0" id="ui-id-1" class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all">
    <li role="presentation" class="ui-menu-item">
        <a tabindex="-1" class="ui-corner-all" id="ui-id-2">agent a</a>
    </li>
    <li role="presentation" class="ui-menu-item">
        <a tabindex="-1" class="ui-corner-all" id="ui-id-3">agent b</a>
    </li>
</ul>
4

1 回答 1

2

Provided I understand the situation, it would probably work cleaner if you just put your 'new item' element after the <ul> and show/hide depending on the situation. Something like this:

HTML

<ul style="display: none; width: 360px; top: 248px; left: 856.5px;" tabindex="0" id="ui-id-1" class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all">
    ...
</ul>
<div id="new-item">
    <label>
        New item
        <input type="text" />
    </label>
</div>

JS

$('#autoc1').focus(function() {
    $('#new-item').show();
});
于 2013-03-30T08:16:56.857 回答