jquery tokeninput,预填充不起作用

时间:2016-07-29 11:04:50

标签: jquery

我使用以下脚本: http://loopj.com/jquery-tokeninput/

但我不能使用“预填充”

这就是我的所作所为:

    $("#select-countries").tokenInput("/api/countries", {   
    theme: "facebook",
    hintText: "Saisissez le nom de pays",
    noResultsText: "Aucun résultat",
    searchingText: "Chargement...",
    searchDelay: 200,
    minChars: 3,
    preventDuplicates: true,
    prePopulate: $.ajax({
        type : 'get',
        url : "/api/countries",
        dataType: "json"
    }).done(function(data) {
        for (var j = 0; j < data.length; j++) {
            prepopulateWards.push({ id: data[j].id, name: data[j].name });
        }
    }),
    onResult: function (results) {
        $.each(results, function (index, value) {
            value.name = value.name;
        });

        return results;
    },
    onAdd: function (item) {
        $('form').append('<input type="hidden" id="country-' + item.id + '" name="countries[]" value="' + item.id + '">');
    },
    onDelete: function (item) {
        $('#country-' + item.id).remove();
    }
});

但它不起作用。一个想法?

谢谢

1 个答案:

答案 0 :(得分:0)

根据官方文档(http://loopj.com/jquery-tokeninput/demo.html#pre-populated),您没有向prePopulate财产返回任何内容。我的建议是:

prePopulate: (function() {
  $.ajax({
    type : 'get',
    url : "/api/countries",
    dataType: "json"
  }).done(function(data) {
    var prepopulateWards = []; // initialise the array
    for (var j = 0; j < data.length; j++) {
        prepopulateWards.push({ id: data[j].id, name: data[j].name });
    }
    return prepopulateWards; // return to prePopulate property
  });

})(),

相关文档中的代码示例:

$("#demo-input-local").tokenInput(
  prePopulate: [
    {id: 7, name: "Ruby"},
    {id: 11, name: "Python"},
    {id: 13, name: "JavaScript"},
    {id: 17, name: "ActionScript"},
    {id: 19, name: "Scheme"},
    {id: 23, name: "Lisp"},
    {id: 29, name: "C#"},
    {id: 31, name: "Fortran"},
    {id: 37, name: "Visual Basic"},
    {id: 41, name: "C"},
    {id: 43, name: "C++"},
    {id: 47, name: "Java"}
  ]
);