jQuery UI .autocomplete()

时间:2011-12-09 04:30:30

标签: javascript jquery json jquery-ui jquery-ui-autocomplete

我在我的网站上使用以下内容进行自动填充:

$(function () {
    $("#client").autocomplete({
        source: "/appointments/clients.json",
        minLength: 1,
        select: function (event, ui) {
            $('input[name="clientid"]').val(ui.item.id);
            $('#app-submit').html('Add Appointment for ' + ui.item.value);
        }
    });
});

我现在要做的是,当用户输入下拉列表中未显示的内容时,我希望以下内容发生:

$('input[name="clientid"]').val('');
$('#app-submit').html('Add Appointment');

我尝试使用以下内容,但它不起作用:

$(function () {
    $("#client").autocomplete({
        source: "/appointments/clients.json",
        minLength: 1,
        select: function (event, ui) {
            if(typeof(ui.item)){
                $('input[name="clientid"]').val(ui.item.id);
                $('#app-submit').html('Add Appointment for ' + ui.item.value);
            } else {
                $('input[name="clientid"]').val('');
                $('#app-submit').html('Add Appointment');
            }
        }
    });
});

2 个答案:

答案 0 :(得分:1)

只有在下拉列表中选择项目时才会触发选择事件 你可以在search event

上做到
$(function () {
    $("#client").autocomplete({
        source: "/appointments/clients.json",
        minLength: 1,
        select: function (event, ui) {
            $('input[name="clientid"]').val(ui.item.id);
            $('#app-submit').html('Add Appointment for ' + ui.item.value);
        },
        search: function() {
            $('input[name="clientid"]').val('');
            $('#app-submit').html('Add Appointment');
        }
    });
});

答案 1 :(得分:0)

如果没有看到标记,我不知道整个想法是什么。但我的猜测是:

$("#client").autocomplete({
    source: function( request, response ) {
        $.ajax({
            url: "/appointments/clients.json",
            dataType: "jsonp",
            success: function( data ) {
                var suggestions = $.map( data, function( item ) {
                    return {
                        label: item.value,
                        value: item.id
                    }
                });
                // idea: whatever I have, extend to extra item.
                suggestions.push({
                    label: 'Add appointment',
                    value: 0
                });
                response( suggestions );
            }
        });
    },
    select: function(evt, ui){
        if( ui.item.label == 'Add appointment'){
            /* do something special with it */
        }else{
            /* blah blah */
        }
    }
});