1. 程式人生 > >bootstrap-table 行內編輯簡單實現

bootstrap-table 行內編輯簡單實現

$('#table').bootstrapTable({
    url: createUrl(''),
    striped: true,
    uniqueId: 'attrValue',
    columns: [{
        title: 'ID',
        field: 'index',
        formatter: formatterIndex
    },{
        title: '規格',
        field: 'attrValue',
        class: 'editable'
    },{
        title: '價格'
, field: 'sellPrice', class: 'editable' },{ title: '操作', field: 'operate', formatter: formatterOperate }] }); function formatterIndex(value, row, index){ var i = index + 1; if(i < 10){ return "0" + i; }else{ return i; } } function
formatterOperate(value, row, index){
return "<button onclick='saveRow("+index+")' class='btn small'><i class='fa fa-edit'></i> 儲存</button><button onclick='editRow("+index+")' class='btn small blue'><i class='fa fa-edit'></i> 編輯</button><button onclick='delRow(\""
+row.attrValue+"\")' class='btn small red'><i class='fa fa-trash-o'></i> 刪除</button>"; } $("#addBtn").click(function(){ var data = { attrValue: '', sellPrice: '' }; $("#table").bootstrapTable('append', data); $("#table tr:last-child td.editable").each(function(){ $(this).html("<input>"); }); }); function saveRow(index, value){ var obj = $("#table tr:nth-child("+ (index+1) +") td.editable"); var attrValue = obj.first().find("input").val().trim(); var sellPrice = obj.last().find("input").val().trim(); var newData = { attrValue: attrValue, sellPrice: sellPrice }; $("#table").bootstrapTable('updateRow', { index: index, row: newData }); obj.find("input").remove(); } function editRow(index){ $("#table tr:nth-child("+ (index+1) +") td.editable").each(function(){ var value = $(this).text(); $(this).html("<input value='"+value+"'>"); }); } function delRow(value){ $("#table").bootstrapTable('removeByUniqueId', value); }