【Handsontable】afterChangeよりもbeforeChange
入力した値を加工したり、入力をキャンセルしたい場合があると思います。
Handsontable(ハンズオンテーブル)では、おそらくbeforeChange
やafterChange
のイベントを使用すると思います。
私的にはbeforeChange
をおすすめします。
理由:afterChange
の場合、2回描画処理が行われてしまうからです。遅いです。
※beforeChange
は、1回なので早いです。
それでは、beforeChange
の使い方をご紹介します。
beforeChange
以下の処理は、入力した値を必ず「OK」に書き変える処理です。
changes
を書き変えることで、入力値の加工や変換が可能です。
$(function(){ // testデータ var data = [ ["", "Ford", "Tesla", "Toyota", "Honda"], ["2017", 10, 11, 12, 13], ["2018", 20, 11, 14, 13], ["2019", 30, 15, 12, 13] ]; // htmlで定義したhandsonTableのID var container = document.getElementById('handsonTable'); var hot = new Handsontable(container, { data: data, beforeChange: function(changes, source) { // 編集、ペースト、オートフィル時 if (source == 'edit' || source == 'CopyPaste.paste' || source == 'Autofill.fill') { // 複数セル対応の為、配列 for (var i = 0; i < changes.length; i++) { var row = changes[i][0]; var col = changes[i][1]; var oldValue = changes[i][2]; var newValue = changes[i][3]; console.log('row:' + row); console.log('col:' + col); console.log('oldValue:' + oldValue); console.log('newValue:' + newValue); // 入力値の上書きも可能 changes[i][3] = 'OK'; } } } }); });
// 例
row:1
col:1
oldValue:おーけー
newValue:OK
changes
:[row, col, oldVal, newVal]
row
:変更した行col
:変更した列oldVal
:変更前の値newVal
:変更後の値
source
:以下のリンクを参照ください。
入力値キャンセル
入力した値をキャンセルすることも容易にできます。
以下の処理は、'edit'以外の場合に入力した値をキャンセルする処理です。
$(function(){ // testデータ var data = [ ["", "Ford", "Tesla", "Toyota", "Honda"], ["2017", 10, 11, 12, 13], ["2018", 20, 11, 14, 13], ["2019", 30, 15, 12, 13] ]; // htmlで定義したhandsonTableのID var container = document.getElementById('handsonTable'); var hot = new Handsontable(container, { data: data, beforeChange: function(changes, source) { if (source != 'edit') { // ペーストやオートフィル等の場合は、編集不可となる。 return false; } } }); });