The editor of easyUI’s DataGrid is ComboBox. When the edit box loses focus, it is saved (including ordinary drop-down box and time date box)

How to write in JSP

 <table id="_list"
			data-options="url:'iface/searchP?p=<s:property value="pd"/>',
					view:scrollview,
					pageSize:50,
					rownumbers:true,
					singleSelect:true,
					autoRowHeight:false,
					extEditing: false,
					idField:'id',
					checkOnSelect: false,
					selectOnCheck: false,
					enableHeaderClickMenu: false,
					enableHeaderContextMenu: false,
					enableRowContextMenu: false,
					border: false,
					fitColumns:true,
					fit: true">
    		<thead frozen="true">
		        <tr>
		        	<th field="ck" checkbox="true"></th>
		        </tr>
		    </thead>
		    <thead>
		        <tr>
		            <th field="practName" width="200" sortable="false" align="center" editor="{type:'text'}">名称</th>
		             <th  field="typeMaskValues" width="150" sortable="false"  align="center" formatter="typeMaskFormatter" editor="{type:'combobox',
            			options:{
            			multiple:true,
            			required:true,
            			url:'iface/findTypeMaskList',valueField:'key',textField:'value',panelHeight:150,
            			editable:false,
            			onHidePanel: onHidePanel,
            			onShowPanel:onShowPanel,
            			onChange:onChange,
	             		onLoadSuccess:function(data){
	             			zdyComboboxArray = data;
	             		}
            			}}">catalog</th>
                      <th field="expiryDate" width="150" sortable="false" align="center" editor="{type:'datebox',options:{required:true,validType:'validDate[\'yyyy-MM-dd\']',
            				onHidePanel: function()
		             		{
		             		    //solve the problem of hand losing (do not execute the blur event, so the assignment in the blur event will not be executed, so here you need to set the dateComboboxObject object in query.js to assign a value)
		                		var textField = $('.datagrid-editable-input').val();
		                		if( textField && textField!=comboboxValue.value){
		                			var row = comboboxValue.row;
		                			row.expiryDate = textField;
		                			changes = 'p';
		                			_destroyCellEditor($(dateComboboxObject.id)[0],{index:dateComboboxObject.rowIndex,field:dateComboboxObject.field});
		                			onAfterEditing(dateComboboxObject.rowIndex,row,dateComboboxObject.changes,dateComboboxObject.id,dateComboboxObject.url,null,{
													onAfterSubmit:function(index, row, changes)
													{
														$('#_list').datagrid('reload');
													}});
		                			endEditing(comboboxValue.id);//This line of code allows the editor to be opened again after the edit box has been destroyed (e.g. double-click to open)
		                		}else{
		                			_destroyCellEditor($('#_list')[0],{index:_rowIndex,field:_field});
		                			endEditing('#_list');
		                		}
		                		_rowIndex = undefined;
		                		_field = undefined;
		                		comboboxValue = {};
		                		dateComboboxObject = {};
		             		},
		             		onSelect: function()
		             		{
		             		},
            			 }}">Expiration Date</th>
		        </tr>
		    </thead>
	</table>

JS corresponding to JSP:

$(function(){
    var p = new Array();
    createTables("#_list", "./iface/modifyP", p);
});
/**
 * Dropdown panel expand event
 */
function onShowPanel(){
}
/**
 * Dropdown panel selection event
 */
function onChange(){
}
/**
 * checkbox hide panel event for datagrid
 */
function onHidePanel(){
	var textField = $('.datagrid-editable-input').val();
	// the dropdown box must be selected, can not be empty
	if(comboboxValue.value && textField && textField!=comboboxValue.value){
	    //mono checkbox
		//var valueField = $('.datagrid-editable-input').next().next().val();
		// checkboxes with multiple input
		var multipleInputs = $('.datagrid-editable-input').nextAll(':input');
		var multipleInputsVal = new Array();
		var j = 0;
		for(var i=0;i<multipleInputs.length;i++){
			var multipleInput = multipleInputs[i];
			var multipleInputVal = multipleInput.value;
			if(multipleInputVal){
				multipleInputsVal[j] = multipleInputVal;
				j++;
			}
		}
		var row = comboboxValue.row;
		row.typeMaskValues = multipleInputsVal;
		row.typeMaskTexts = textField;
		var options = {};
		options.onAfterSubmit = afterSubmit;
		_destroyCellEditor($(comboboxValue.id)[0],{index:comboboxValue.rowIndex,field:comboboxValue.field});
		onAfterEditing(comboboxValue.rowIndex,row,comboboxValue.changes,comboboxValue.id,comboboxValue.url,new Array(),options);
		endEditing(comboboxValue.id);//This line of code allows the editor to be opened again after the edit box has been destroyed (e.g. double-click to open)
	}else{
		_destroyCellEditor($('#_list')[0],{index:_rowIndex,field:_field});
		endEditing('#_list');
		comboboxValue["data"] = comboboxValue.row;
		afterSubmit(comboboxValue.rowIndex, comboboxValue.row, "",comboboxValue,comboboxValue.id);
	}
	 _rowIndex = undefined;
	 _field = undefined;
	 _rowId = undefined;
	comboboxValue = {};
}

Double click the DataGrid of easyUI to open the general JS of the edit dialog box

//Validation of time frames
$.extend($.fn.datebox.defaults.rules, { 
	validDate: {  
		validator: function(value){  
			var date = $.fn.datebox.defaults.parser(value);
			var s = $.fn.datebox.defaults.formatter(date);
			return s==value; 
		},  
		message: 'Please enter the correct date:e.g.:2016-06-08'  
	}
});

/**
 * Create a generic JS that can edit the table online
 * @param table table object
 * @param url update url
 * @param arrays array of data
 * @param options Parameters of the table
 */
function createTables(table,url,arrays,options)
{
	$(table).datagrid({
		autoEditing: false,
		autoWrapEdit: false,
		height:$("#datagridPanel").height(),//The ID of the layout of the easyui where the datagrid is located
		onLoadSuccess:function(node,data)
		{
			$(table).datagrid('clearSelections');
    		$(table).datagrid('clearChecked');
			$.fn.datagrid.extensions.onLoadSuccess.apply(this, arguments);
			if (options && options.onLoadSuccess && $.isFunction(options.onLoadSuccess))
			{
				options.onLoadSuccess(node,data);
			}
		},
		onBeforeEdit: function (index, row)
		{
			$.fn.datagrid.extensions.onBeforeEdit.apply(this, arguments);
			//Before editing, put the original data into the arrays array, using row.id as subscript
			arrays[row.id]=new Object();
			for (var key in row)
			{
				if (!$.isArray(row[key]) && !$.isFunction(row[key])
						&& (typeof row[key]) == "object" && row[key]!=null)
				{
					continue;
				}
				//The row that is put into arrays here is the unmodified row object, with row.id as the subscript index
				arrays[row.id][key]=row[key];
			}
		},
		onEndEdit:	function(index, row, changes)
		{
			if (options && options.onEndEdit && $.isFunction(options.onEndEdit))
			{
				options.onEndEdit(index, row, changes);
			}
		},
		onAfterEdit: function (index, row, changes)
		{
			return false;//The following method is not used for the time being (do not call easyui's datagrid default editing method)
            //changes is an object object, formatted as: Object {price: "1.00"}
			//note that the row is after the end of the edit (i.e., after the modification of the row object), and arrays[row.id] in the row is modified before the id
			$.fn.datagrid.extensions.onAfterEdit.apply(this, arguments);
			if (options && options.onAfterEdit && $.isFunction(options.onAfterEdit))
			{
				options.onAfterEdit(index, row, changes);
			}
			var t=false;
			for (var key in arrays[row.id])
			{
				//Here compare the line after the end of editing and the original line of the value of whether there is a difference, as long as there is, send a url request, and send the back of the row to the server, and modify the save
				if (row[key]!=arrays[row.id][key])
				{
					t=true;
					break;
				}
			}
			if (t)
			{
				//Initialize the data object to be passed by post
				var data={"id":row.id};
				for (var key in row)
				{
					if (!$.isArray(row[key]) && !$.isFunction(row[key])
							&& (typeof row[key]) == "object")
					{
						continue;
					}
					data["object."+key]=row[key];
				}
				$.post(url,data,function(data){
					var obj=eval('('+data+')');
					if (obj && obj.returnCode==1)
					{
						if (options && options.onAfterSubmit && $.isFunction(options.onAfterSubmit))
						{
							options.onAfterSubmit(index, row, changes);
						}
						return;
					}
					$.messager.alert('error',obj.message,'error');
				});				
			}
			arrays[row.id]=new Object();//Clear the original arrays array
		},
		onCheck:function(rowIndex,rowData){
			if (options && options.onCheck && $.isFunction(options.onCheck))
			{
				options.onCheck(rowIndex,rowData);
			}
		},
		onSelect:function(rowIndex, rowData)
		{
			if (options && options.onSelect && $.isFunction(options.onSelect))
			{
				options.onSelect(rowIndex,rowData);
			}		
		},
		onCheckAll:function(rows){
			if (options && options.onCheckAll && $.isFunction(options.onCheckAll))
			{
				options.onCheck(rows);
			}
		},
		onClickCell:function(rowIndex, field, value)
		{
            if (options && options.onClickCell && $.isFunction(options.onClickCell))
			{
				options.onClickCell(rowIndex, field, value);
			}
		},
		onClickRow:function(rowIndex, rowData)
		{
		},
        //Double-click a cell to open a cell edit
		onDblClickCell: function(rowIndex, field, value){
			var rowData = $(table).datagrid('getRowData',rowIndex);
			if (options && options.onDblClickCell && $.isFunction(options.onDblClickCell))
			{
				options.onDblClickCell(rowIndex, rowData);
			}else{
				var id = table;
				onClickRow(rowIndex, field, value,id,url,arrays,options);
			}
		},
	});
}

var comboboxValue = {};//The drop-down box is used to save the data object
var dateComboboxObject = {};//The object used to save data in the time and date box
/**
 * open click cell
 * 
 */
var _rowIndex = undefined;
var _field = undefined;
var _rowId=undefined;
function onClickRow(rowIndex, field, value,id,url,arrays,options) {
	var columnOption=$(id).datagrid("getColumnOption",field);
	if(columnOption && columnOption.readonly == true)
		return false;
	if(refreshRowFlag){
		$(id).datagrid("refreshRow", rowIndex);
	};
    if (_rowIndex != rowIndex || _field != field) {
        if (endEditing(id)){
        	$(id).datagrid('selectRow',rowIndex);
        	
            $(id).datagrid('beginEditCell', {index: rowIndex, field: field});
            var ed = $(id).datagrid('getEditor', {index:rowIndex,field:field});
            if(ed == null)
            	return false;
            _rowIndex = rowIndex;
            _field = field;
            _rowId=id;
            
            var row=$(id).datagrid("getRowData",rowIndex);
            if(ed.type == 'combobox'){
            	//As soon as the dropdown box is edited, then click on the inverted triangle to open the dropdown panel options
            	$(".datagrid-editable-input").next('span').find('.combo-arrow').click();
            	$(".datagrid-editable-input").focus();
            	comboboxValue.row= row;
            }else{
            	$(".datagrid-editable-input").focus(function(){
            		this.select();
            	});
            	if(ed.type == 'datebox'){
            		comboboxValue.row= row;
            		$(".datagrid-editable-input").focus();
            		//Solve the problem of the time box hand lost, do not execute the blur event, directly execute onHidePanel function ...
            		dateComboboxObject["id"] = id;
        			dateComboboxObject['rowIndex'] = rowIndex;
        			dateComboboxObject['field'] = field;
        			dateComboboxObject['status'] = 'p';
        			dateComboboxObject['url'] = url;
        			dateComboboxObject['changes'] = changes;
            	}else{
            		$(ed.target).focus();
            	}
            }
        	$(".datagrid-editable-input").blur(function(){
        		var changes={};
        		if(ed.type=='combobox' || ed.type == 'datebox'){
        			//It should be noted that if it is a drop-down box, there are two cases:
        			//1/1. If the dropdown panel is clicked, then the blur() event of .datagrid-editable-input will be executed first, then the comboboxValue will be assigned, and then the onHidePanel event will be executed.
        			//If you didn't click on the dropdown panel, but just clicked on other parts of the panel and lost focus, then the onHidePanel event will be executed first, and then the blur() event of the datagrid-editable-input will be executed, at this time the comboboxValue is not assigned a value (only a row property is assigned, other properties are not is assigned)
        			//1/1 and 2, the closing of the drop-down edit box is put into onHidePanel
        			comboboxValue.id = id;
        			comboboxValue.rowIndex = rowIndex;
        			comboboxValue.field = field;
        			changes['status'] = "p";
//            		comboboxValue.row = row;
        			comboboxValue.url = url,
        			comboboxValue.changes = changes;
        			comboboxValue.value = $(".datagrid-editable-input").val();
        			
        		}else {
        			if(ed.type=='checkbox'){
        				_destroyCellEditor($(id)[0],{index:rowIndex,field:field});
        				var state = $(this).prop('checked');
        				var obj = checkbox(row,state);
        				if(obj.state){
        					changes["status"]="P";
        					onAfterEditing(rowIndex,row,changes,id,url,arrays,options);
        				}
        			}else {
        				_destroyCellEditor($(id)[0],{index:rowIndex,field:field});
        				var oldVal=row[field];
        				var newVal=this.value;
        				if(oldVal!=newVal){
        					changes[field]=newVal;
        					row[field]=newVal;
        					changes["status"]="P";
        					onAfterEditing(rowIndex,row,changes,id,url,arrays,options);            			
        				}
        			}
        			//Because these two variables are needed in the onHidePanel of the drop-down box, the emptying of these two variables should be executed in the hiddenpanel
        			_rowIndex = undefined;
        			_field = undefined;
        		}
        	});
            var rows=$(id).datagrid("getRows");
            $(ed.target).bind('keydown', function()
            {
            	switch (window.event.keyCode) {
				case 13://enter
					$(this).blur();
					endEditing(id);
					event.returnValue=false; 
					if(rowIndex<rows.length-1){
						onClickRow(rowIndex+1,field,value,id,url,arrays,options);
					}
					break;
				case 37://left
					$(this).blur();
					//Stop the editing of the previous box
					endEditing(id);
					//Disable default keyboard events
					event.returnValue=false; 
					var prevfiled=$(id).datagrid("prevColumn",field);
					if(prevfiled!=null&&prevfiled.editor){
						onClickRow(rowIndex,prevfiled.field,value,id,url,arrays,options);
					}
					break;
				case 38://up
					$(this).blur();
					endEditing(id);
					event.returnValue=false; 
					if(rowIndex>0){
						onClickRow(rowIndex-1,field,value,id,url,arrays,options);
					}
					break;
				case 39://right
					$(this).blur();
					endEditing(id);
					event.returnValue=false; 
					var nextfiled=$(id).datagrid("nextColumn",field);
					if(nextfiled!=null&&nextfiled.editor){
						onClickRow(rowIndex,nextfiled.field,value,id,url,arrays,options);
					}
					break;
				case 40://down
					$(this).blur();
					endEditing(id);
					event.returnValue=false; 
					if(rowIndex<rows.length-1){
						onClickRow(rowIndex+1,field,value,id,url,arrays,options);
					}
					break;
				case 27:// Escape Escape 
					$(this).blur();
					endEditing(id);
					break;
				}
            });
        }
    }
    return true;
}  
/**
 * 
 */
function endEditing(id) {
    if (_rowIndex == undefined || _field == undefined || id == undefined) {
        return true;
    }

    $(id).datagrid('endEditCell', {index: _rowIndex, field: _field});
    _rowIndex = undefined;
    _field = undefined;
    _rowId = undefined;
    return true;
}
/**
 * Rewrite the methods in datagrid
 */
$.extend($.fn.datagrid.methods, {
    beginEditCell: function (target, options) {
        return target.each(function () {
            beginEditCell(this, options);
        });
    },
    endEditCell: function (target, options) {
        return target.each(function () {
            endEditCell(this, options);
        });
    }
});
//Turn on editing cell status
function beginEditCell(target, options) {

//    var opts = $.data(target, "datagrid").options;
//    var tr = opts.finder.getTr(target, options.index);
//    var row = opts.finder.getRow(target, options.index);

//    if (tr.hasClass("datagrid-row-editing")) {
//        return;
//    }
//    tr.addClass("datagrid-row-editing");

    _initCellEditor(target, options.index, options.field);
    _outerWidthOfEditable(target);
//    $.validateRow(target, options.index);I don't know how to use this method for now.
}
/**
 * Initialize the form editor
 */
function _initCellEditor(target, _index, _field) {
    var opts = $.data(target, "datagrid").options;
    var tr = opts.finder.getTr(target, _index);
    var row = opts.finder.getRow(target, _index);

    tr.children("td").each(function () {
        var cell = $(this).find("div.datagrid-cell");
        var field = $(this).attr("field");

        if (field == _field) {//Find the cell with the same field as the passed parameter
            var col = $(target).datagrid("getColumnOption", field);
            if (col && col.editor) {
                var editorType, editorOp;
                if (typeof col.editor == "string") {
                    editorType = col.editor;
                } else {
                    editorType = col.editor.type;
                    editorOp = col.editor.options;
                }
                var editor = opts.editors[editorType];
                if (editor) {
                    var html = cell.html();
                    var outerWidth = cell._outerWidth();
                    cell.addClass("datagrid-editable");
                    cell._outerWidth(outerWidth);
                    cell.html("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td></td></tr></table>");
                    cell.children("table").bind(
                        "click dblclick contextmenu",
                        function (e) {
                            e.stopPropagation();
                        });
                    $.data(cell[0], "datagrid.editor", {
                        actions: editor,
                        target: editor.init(cell.find("td"),
                            editorOp),
                        field: field,
                        type: editorType,
                        oldHtml: html
                    });
                }
            }
            
            $('.datagrid-editable').css('height','auto');//Set the style of the div that wraps the editorde
            $('.datagrid-editable-input').css("line-height","");//set the style of the edit box
            
            tr.find("div.datagrid-editable").each(function () {
                var field = $(this).parent().attr("field");
                var ed = $.data(this, "datagrid.editor");
                var val = row[field];
                if(ed.type == 'combobox'){
                	var opts = $(ed.target).combobox("options");
                    // If the dropdown box can be multi-selected, the value of the dropdown box must be set to include, because it will be split by "," when the edit box is initialized
                	if(opts.multiple){
                		val = val+",";
                	}
                }
                ed.actions.setValue(ed.target, val);
            });
        }
    });
}
//Set outer borders for editable cells
// function _4d8() method from jquery.easyui.1.8.0.js
function _outerWidthOfEditable(target) {
    var dc = $.data(target, "datagrid").dc;
    dc.view.find("div.datagrid-editable").each(function () {
        var _this = $(this);
        var field = _this.parent().attr("field");
        var col = $(target).datagrid("getColumnOption", field);
        _this._outerWidth(col.width);
        var ed = $.data(this, "datagrid.editor");
        if (ed.actions.resize) {
            ed.actions.resize(ed.target, _this.width());
        }
    });
}
//Destroy cell editor
function _destroyCellEditor(target, options) {

    var opts = $.data(target, "datagrid").options;
    var tr = opts.finder.getTr(target, options.index);
    tr.children("td").each(function () {
        var field = $(this).attr("field");
        if (field == options.field) {//Find the cell with the same field as the passed parameter

            var cell = $(this).find("div.datagrid-editable");
            if (cell.length) {
                var ed = $.data(cell[0], "datagrid.editor");
                if (ed.actions.destroy) {
                    ed.actions.destroy(ed.target);
                }
                cell.html(ed.oldHtml);
                $.removeData(cell[0], "datagrid.editor");
                cell.removeClass("datagrid-editable");
                cell.css("width", "");
            }
        }
    });
}

function onAfterEditing(rowIndex,row,changes,id,url,arrays,options){
	var saveData=save(rowIndex,row,changes,id,url,arrays,options);
	row=saveData[0];
	changes=saveData[1];
	afterEdit(rowIndex,row,changes,id);
}
function afterEdit(rowIndex, rowData, changes,id){
    $(id).datagrid('updateRow',{
        index: rowIndex,
        row: rowData
    });
    $(id).datagrid('acceptChanges');
    
    //Rendering of the "Customer Order Management" icon
	if(refreshLinkbutton2 !=undefined && $.isFunction(refreshLinkbutton2)){
		refreshLinkbutton2(rowData);
	}
	
}
/**
 * @param rowSave data after editing cell changes
 * @param changes
 * row is the modified row, not the original row
 * @returns {Array}[0] means row, [1] means changes
 */
function save(index,row,changes,id,url,arrays,options)
{
	var data={"id":row.id};
	for (var key in row)
	{
		if (!$.isArray(row[key]) && !$.isFunction(row[key])
				&& (typeof row[key]) == "object")
		{
			continue;
		}
		data["object."+key]=row[key];
	}
	$.post(url,data,function(data){
		var obj=eval('('+data+')');
		if (obj && obj.returnCode==1)
		{
			if (options && options.onAfterSubmit && $.isFunction(options.onAfterSubmit))
			{
				options.onAfterSubmit(index, row, changes,obj,id);
			}
			return;
		}
		//$("#_list").datagrid('rejectChanges'); 
		$("#_list").datagrid('reload');
		$.messager.alert('error',obj.message,'error');
	});				
	var saveData=new Array();
		saveData[0]=row;//used as a datagrid updateRow parameters, note that there are some special cases, the row is changed after the row, but some of the values need to be passed to the action did not change, such as queryRateValues.jsp.js
		saveData[1]=changes;
		return saveData;
}
//close the edit cell state
function endEditCell(target, options) {
    var opts = $.data(target, "datagrid").options;

    var updatedRows = $.data(target, "datagrid").updatedRows;
    var insertedRows = $.data(target, "datagrid").insertedRows;

    var tr = opts.finder.getTr(target, options.index);
    var row = opts.finder.getRow(target, options.index);

//    //echoes the beginEditCell, temporarily cancelled
// if (!tr.hasClass("datagrid-row-editing")) {// When row cannot be edited, return
//        return;
//    }
//    tr.removeClass("datagrid-row-editing");

    var _535 = false;
    var _536 = {};
    tr.find("div.datagrid-editable").each(function () {
        var _537 = $(this).parent().attr("field");
        var ed = $.data(this, "datagrid.editor");
        var _538 = ed.actions.getValue(ed.target);
        if (row[_537] != _538) {
            row[_537] = _538;
            _535 = true;
            _536[_537] = _538;
        }
    });
    if (_535) {
        if (_45f(insertedRows, row) == -1) {
            if (_45f(insertedRows, row) == -1) {
                updatedRows.push(row);
            }
        }
    }
    
    _destroyCellEditor(target, options);
    $(target).datagrid("refreshRow", options.index);
    opts.onAfterEdit.call(target, options.index, row, _536);
}

function _45f(a, o) {
    for (var i = 0, len = a.length; i < len; i++) {
        if (a[i] == o) {
            return i;
        }
    }
    return -1;
}

Similar Posts: