2011-12-09 80 views
0

我有自动完成我的网站上的工作有以下: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'); 
      } 
     } 
    }); 
}); 

回答

1

当您在下拉列表中选择一个项目 你能做到这一点的选择evevnt时才会触发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'); 
     } 
    }); 
}); 
0

我不是k现在什么是整个想法是没有看到标记。但我的猜测是:

$("#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 */ 
     } 
    } 
});