如何使用Handsontable更新基于另一个自动完成单元格的单元格

时间:2014-09-22 14:52:18

标签: javascript jquery ajax handsontable

我已经拥有完整的代码来返回自动填充数据并根据此自动填充功能填充其他单元格 但我想让它从ajax请求动态到数据库查询。 怎么做?

http://jsfiddle.net/wvXvJ/15/

$(document).ready(function() {

        var $container  = $("#mytables");
        var comsources  = ["Chrysler", "Nissan", "Suzuki", "Toyota"];

        var ac = [
            {"name":"Chrysler","label":"Pepsi Cola Hat","price":"24","abbrev":"CRY"},
            {"name":"Nissan","label":"Candle Lights Dinner","price":"780","abbrev":"NSS"},
            {"name":"Suzuki","label":"Pork Meat Ball","price":"178","abbrev":"SZK"},
            {"name":"Toyota","label":"Granny Health Supplement","price":"24","abbrev":"TYT"}
        ];

        var ht = $container.handsontable({
            startRows: 1,
            startCols: 5,
            rowHeaders: true,
            colHeaders: ['Item Name', 'Price', 'Code'],
            minSpareRows: 1,
            contextMenu: true,
            columns: [
                {
                    data: "name",
                    type: 'autocomplete',
                    source: comsources,
                    strict: false
                },
                {
                    data: "price"
                },
                { 
                    data: "code"
                }
            ],
            afterChange : function(arr, op) {
                if(op=="edit"&&arr.length==1) {
                    var value = arr[0][3];
                    for(var i=0;i<ac.length;i++) {
                        if(ac[i].name == value) {
                            $container.handsontable("setDataAtCell", arr[0][0], 1, ac[i].price);
                            $container.handsontable("setDataAtCell", arr[0][0], 2, ac[i].abbrev);
                            return false;
                        }
                    }
                }
            }
        });
    });

1 个答案:

答案 0 :(得分:3)

他们在documentation

中确切地定义了如何做到这一点
$("#example3").handsontable({
  data: getCarData(),
  startRows: 7,
  startCols: 4,
  colHeaders: ["Car", "Year", "Chassis color", "Bumper color"],
  columns: [
    {
      type: 'autocomplete',
      source: function (query, process) {
        $.ajax({
          //url: 'php/cars.php', //commented out because our website is hosted on static GitHub Pages
          url: 'json/autocomplete.json',
          dataType: 'json',
          data: {
            query: query
          },
          success: function (response) {
              console.log("response", response);
              //process(JSON.parse(response.data)); //JSON.parse takes string as a argument
              process(response.data);

          }
        });
      },
      strict: true
    },
    {} /*Year is a default text column*/,
    {} /*Chassis color is a default text column*/,
    {} /*Bumper color is a default text column*/
  ]
});