2011-12-09 114 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 */ 
     } 
    } 
});