2014-02-26 61 views
0

我正在使用JQuery自動填充類別讓用戶從列表中選擇一個項目。允許用戶添加項目到JQuery自動完成類別

我現在想要做的是讓用戶添加一個新的項目到兩個可用的類別之一。

這是我現在有:

HTML:

<input id="procura"></input> 

JS:

$.widget("custom.catcomplete", $.ui.autocomplete, { 
    _renderMenu: function (ul, items) { 
     var that = this, 
      currentCategory = ""; 
     $.each(items, function (index, item) { 
      if (item.category != currentCategory) { 
       ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>"); 
       currentCategory = item.category; 
      } 
      that._renderItemData(ul, item); 
     }); 
    } 
}); 

$(function() { 
    var data = [{ 
     label: "Vendas", 
     category: "Recebimentos" 
    }, { 
     label: "Serviços", 
     category: "Recebimentos" 
    }, { 
     label: "Outros", 
     category: "Recebimentos" 
    }, { 
     label: "Fornecedores", 
     category: "Pagamentos" 
    }, { 
     label: "FSW", 
     category: "Pagamentos" 
    }, { 
     label: "Outros", 
     category: "Pagamentos" 
    }]; 

    $("#procura").catcomplete({ 
     delay: 0, 
     source: data 
    }); 
}); 

的jsfiddle here

回答

1

你需要添加輸入收集新要添加到下拉菜單中的項目以及應該添加的項目被添加。然後,只需將新項目推送到數據數組。

下面的代碼是基於你提供了什麼擴展,雖然你需要添加到它使用戶可以選擇一個類別:

HTML:

<input id="procura"></input> 
<br> 
New Item: 
<input id="new_item"></input><button onclick="add_item();">Add</button> 

JS:

$.widget("custom.catcomplete", $.ui.autocomplete, { 
_renderMenu: function (ul, items) { 
    var that = this, 
     currentCategory = ""; 
    $.each(items, function (index, item) { 
     if (item.category != currentCategory) { 
      ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>"); 
      currentCategory = item.category; 
     } 
     that._renderItemData(ul, item); 
    }); 
} 
}); 

var data = [{ 
    label: "Vendas", 
    category: "Recebimentos" 
}, { 
    label: "Serviços", 
    category: "Recebimentos" 
}, { 
    label: "Outros", 
    category: "Recebimentos" 
}, { 
    label: "Fornecedores", 
    category: "Pagamentos" 
}, { 
    label: "FSW", 
    category: "Pagamentos" 
}, { 
    label: "Outros", 
    category: "Pagamentos" 
}]; 

function add_item() 
{ 
    var add_to_list = {}; 
    add_to_list['label'] = $('#new_item').val();; 
    add_to_list['category'] = "Recebimentos"; // ADD INPUT TO CHOOSE 
    data.push(add_to_list); 
    $('#new_item').val(''); 
} 

$(function() { 

    $("#procura").catcomplete({ 
     delay: 0, 
     source: data 
    }); 
}); 

在這裏看到的jsfiddle:http://jsfiddle.net/E9eWa/10/

這個答案也provi des similar similar insight:Adding values to jQuery autocomplete real time

相關問題