jqgrid中edittype为text、CheckBox、select、textarea、function等,为jqgrid添加自定义按钮

这篇博客介绍了如何在jqgrid中为不同类型的列(text、CheckBox、select)添加自定义操作按钮,包括绑定绑定合同号和上传附件的功能。通过示例代码展示了如何使用ajax获取下拉列表数据,并在单元格中添加编辑和查看的交互功能。
<script type="text/javascript">
		
			/********获取贸易商名称下拉列表*************/
			function getVal(){
				var nameVal = "";
				var i = 0;
				$.ajax({
					type : "GET",
					async : false,
					url : "trader_queryPageTrader.do",	//向后台请求数据
					success : function(result){
						var result = eval('('+ result +')');
						var resultContent = result.root;
						for(i; i < resultContent.length; i++){
					    	if(i != resultContent.length - 1){
					    		nameVal += resultContent[i].traderName + ":" + resultContent[i].traderName + ";";
					    	}else{
					    		nameVal += resultContent[i].traderName + ":" + resultContent[i].traderName;
					    	}
						}  
					}
				});
				return nameVal;
			}
	
			/********取大宗物资网合同号**********/
			$.ajax({
				async:false,
				cache:true,
	            type: "POST",  
	            url: "goodsDzContract_queryDzPurchaseNum.do",	//向后台请求数据
	            success: function(result){
					var result = eval('('+ result +')');
					if(result != undefined && result.length > 0){
	                	for ( var i = 0; i < result.length; i++) {	
	                        var opt = "<option value='" + result[i].purchaseNum + "'>" + result[i].purchaseNum + "</option>";  
	                        $("#DzContractNum").append(opt);
	                    } 
	                }
	            },  
	            error: function() {  
	                alert("获取大宗物资网合同号失败")  
	            }  
	        });
			
			/*********绑定合同号弹出框************/
			function bindAttachment(id){
				var rowData = $("#grid-table").jqGrid('getRowData',id);
				var goodsOrder = rowData.goodsOrder;
				var goodsPackage = rowData.goodsPackage;
				$("#orderId1").val(goodsOrder);			//订单号:document.getElementById("orderId").value = goodsOrder;
				$("#bindContractDialog").dialog({ 
					autoOpen:true,
					height:300, 
					width:330,  
					resizable:false, 
					modal:true, //这里就是控制弹出为模态 
					buttons:{ 
						"确定":function(){
							var id = rowData.id;
							var dzPurchaseContractNum = $("#DzContractNum2").val();
							//向后台提交数据
							$.ajax({
								async:false,
								cache:true,
							    type: "POST",
							    data:{
									id:id,
									dzPurchaseContractNum:dzPurchaseContractNum,
								}, 
							    url: "goods_boundContractNum.do", 	//获取json数据  
							    success: function(){
									alert("绑定合同号成功");
									window.location.href = "./traderGoodsInfo.html";
							    },  
							    error: function() {
							        alert("绑定合同号失败")  
							    }  
							});
							$(this).dialog("close"); 
						},  
						"取消":function(){$(this).dialog("close");} 
					}
				});
			}
			
			/*******
				上传附件弹出框
			********/
			function uploadAttachment(id) {
				var rowData = $("#grid-table").jqGrid('getRowData',id);
				var goodsOrder = rowData.goodsOrder;
				var goodsId = rowData.id;
				$("#goodsId").val(goodsId);
				$("#orderId2").val(goodsOrder);			//订单号:document.getElementById("orderId").value = goodsOrder;
				$("#uploadFileDialog").dialog({ 
					autoOpen:true,
					height:365, 
					width:400,  
					resizable:false, 
					modal:true //这里就是控制弹出为模态 
				});
			}
			
			/**********添加多文件上传************/
			function plusFile(){
				//<input type='button' value='删除' onclick='deleteCurrent(this)' style='display:inline;'/>
				$("#otherFile").append("<p style='margin-top:-2px;'><input type='file' name='file' style='display:inline; width:180px;'/><button type='button' class='btn btn-danger btn-xs' style='border-radius:4px; margin-top:-5px;' onclick='deleteCurrent(this)'><i class='icon-trash icon-on-right bigger-110'></i>删除</button></p>");
			}
				
			/**********删除多文件上传***********/
			function deleteCurrent(obj){
				$(obj).parent().remove();
			}
		
			
			var grid_data = 
			[ 
				{id:"1",name:"张三",note:"长文本1",stock:"是",ship:"一年级", sdate:"2007-12-03"},
				{id:"2",name:"李四",note:"长文本2",stock:"否",ship:"二年级",sdate:"2007-12-03"},
				{id:"3",name:"王二",note:"长文本3",stock:"否",ship:"五年级",sdate:"2007-12-03"},
				{id:"4",name:"小五",note:"长文本4",stock:"是",ship:"四年级",sdate:"2007-12-03"},
				{id:"5",name:"六六",note:"长文本5",stock:"是",ship:"三年级",sdate:"2007-12-03"},
				{id:"6",name:"九儿",note:"长文本6",stock:"否", ship:"六年级",sdate:"2007-12-03"},
				{id:"7",name:"石榴",note:"长文本7",stock:"是",ship:"一年级",sdate:"2007-12-03"},
				{id:"8",name:"一一",note:"长文本8",stock:"否",ship:"三年级",sdate:"2007-12-03"}
			];	
			
			jQuery(function($) {
				var grid_selector = "#grid-table";
				var pager_selector = "#grid-pager";			
				jQuery(grid_selector).jqGrid({
					//direction: "rtl",					
					data: grid_data,
					datatype: "local",
					height: 400,
					
					/****列显示名称******/
					colNames:[' ', '绑定及上传', 'id','日期','名称', '复选框', '下拉框', '备注', '超链接1', '超链接2', '上传照片'],
					
					/*********************************				
							常用到的属性:name:列显示的名称;index:传到服务器端用来排序用的列名称;width:列宽度;align:对齐方式;sortable:是否可以排序
			 				edittype:可以编辑的类型。可选值:text, textarea, select, checkbox, password, button, image, file。 默认为text。
			 				unformat:可以为formatter指定自定义格式的方法,比如:pickDate, aceSwitch,  function,  null
					************************************/
					colModel:[
						{name:'myac',index:'', width:80, fixed:true, sortable:false, resize:false,
							formatter:'actions', 
							formatoptions:{ 
								keys:true,							
								delOptions:{recreateForm: true, beforeShowForm:beforeDeleteCallback},
							}
						},
						
						{name:'myac222',index:'', width:80, fixed:true, sortable:false, resize:false,
							formatter: function (value, grid, rows, state) {
								return "<a href=\"#\" title=\"绑定合同\" style=\"margin-left:10px\" onclick=\"bindAttachment(" + rows.id + ")\"><i class=\"icon-cogs purple\" style=\"font-size:15px\"></i></a><a href=\"#\" style=\"margin-left:12px\" title=\"上传计划单\" onclick=\"uploadAttachment(" + rows.id + ")\"><i class=\"icon-cloud-upload blue\" style=\"font-size:15px\"></i></a>"; 
							}
						},
						
						/******此id一般为数据库中的主键,一般不显示出来*********/
						/******字段隐藏及显示问题:
								1.新增或展示时都不显示字段:hidden: true  
								2.新增时显示,展示时不显示:editrules: {edithidden: true}, hidden:true
								3.新增时不显示,展示时显示:editable: false
						************/
						{name:'id', index:'id', width:60, sorttype:"int", editable: true, hidden:true},
						
						/******unformat: pickDate   此处使用了datepicker插件来显示时间******/
						{name:'sdate', index:'sdate', width:60, editable:true, sorttype:"date", unformat: pickDate},
						
						/*******默认edittype为text**************/
						{name:'name', index:'name', width:60, editable: true, editoptions:{size:"20", maxlength:"30"}},
						
						/*******edittype:"checkbox", editoptions:{value:"是:否"}  复选框。   unformat:aceSwitch 自定义设置复选框样式***********/
						{name:'stock', index:'stock', width:60, editable: true, edittype:"checkbox", editoptions:{value:"是:否"}, unformat:aceSwitch},
						
						/*******edittype:"select", editoptions:{value: "一:一年级;二:二年级;三:三年级"}  下拉框第一种赋值方法,特别注意下拉框最后一行内容后面不能有分号";",否则下拉内容会多出一个undefined************/
						/*******edittype:"select", editoptions:{value: {1:'在用', 2:'空闲', 3:'故障'}}  下拉框第二种赋值方法*******/
						/*******edittype:"select", editoptions:{value: getVal()}  下拉框第三种赋值方法,然后再实现getVal()方法,以返回此下拉框内容*************/
						{name:'ship', index:'ship', width:60, editable: true, edittype:"select", editoptions:{value:"一:一年级;二:二年级;三:三年级;四:四年级;五:五年级;六:六年级"}},
						
						/*******edittype:"textarea", editoptions:{rows:"2",cols:"10"}*******/
						{name:'note', index:'note', width:60, sortable:false, editable:true, edittype:"textarea", editoptions:{rows:"2",cols:"10"}},
						
						/*******formatter:function(cellvalue, options, rowObject){return "<a href=\"../index.html\">监控</a>";}   超链接跳转页面,也可以在gridComplete中循环为每一行添加超链接,此时还可以给跳转页面传递参数****/
						{name:'monitor',index:'monitor', width:60, sortable:false, editable:false, formatter:function(cellvalue, options, rowObject){return "<a href=\"../index.html\">监控</a>";}},
						
						/*******在gridComplete中循环为每一行添加超链接,此时还可以给跳转页面传递参数*********/
						{name:'detail',index:'detail', width:60, sortable:false, editable:false},
						
						{name:'myac111',index:'', width:120, fixed:true, sortable:false, resize:false, align: "center",
							formatter: function (value, grid, rows, state) {
								return "<a href=\"#\" title=\"上传司机照片\" style=\"margin-left:10px\" onclick=\"uploadAttachment(" + rows.id + ")\"><i class=\"icon-cloud-upload blue\" style=\"font-size:15px\"></i></a>"; 
							}
						},
					],
					
					rownumbers: true,		//添加左侧行号
					viewrecords : true,
					rowNum:10,
					rowList:[10,20,30],
					pager : pager_selector,
					altRows: true,
					//toppager: true,					
					multiselect: true,
					//multikey: "ctrlKey",
			        multiboxonly: true,
			        
			        gridComplete:function(){ //在此事件中循环为每一行添加修改和删除链接 
						var ids=jQuery("#grid-table").jqGrid('getDataIDs'); 					//获取单个id	
						for(var i = 0; i<ids.length; i++){ 
							var id = ids[i];
							//var rowData = $("#grid-table").jqGrid('getRowData',id);
							//var goodsStatus = rowData.goodsStatus;
							
							details = '<a href="../index.html?id='+id+'&goodsStatus=2">查看附件</a>';		//向跳转页面传递参数
		                    jQuery("#grid-table").jqGrid('setRowData', ids[i], { detail: details});
							
						} 
					},
			        
					loadComplete : function() {
						var table = this;
						setTimeout(function(){
							styleCheckbox(table);
							updateActionIcons(table);
							updatePagerIcons(table);
							enableTooltips(table);
						}, 0);
					},			
					editurl: "",//nothing is saved
					caption: "测试列表",						
					autowidth: true			
				});
					
				//switch element when editing inline
				function aceSwitch( cellvalue, options, cell ) {
					setTimeout(function(){
						$(cell) .find('input[type=checkbox]')
								.wrap('<label class="inline" />')
							.addClass('ace ace-switch ace-switch-5')
							.after('<span class="lbl"></span>');
					}, 0);
				}

				//enable datepicker
				function pickDate( cellvalue, options, cell ) {
					setTimeout(function(){
						$(cell) .find('input[type=text]')
								.datepicker({format:'yyyy-mm-dd' , autoclose:true}); 
					}, 0);
				}			
			
				//navButtons
				jQuery(grid_selector).jqGrid('navGrid',pager_selector,
					{ 	//navbar options
						edit: true,
						editicon : 'icon-pencil blue',
						add: true,
						addicon : 'icon-plus-sign purple',
						del: true,
						delicon : 'icon-trash red',
						search: true,
						searchicon : 'icon-search orange',
						refresh: true,
						refreshicon : 'icon-refresh green',
						view: true,
						viewicon : 'icon-zoom-in grey',
					},

					{
						//edit record form
						//closeAfterEdit: true,
						recreateForm: true,
						beforeShowForm : function(e) {
							var form = $(e[0]);
							form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
							style_edit_form(form);
						},
						afterComplete: function(e) {
							alert("修改成功!");
							location.reload();
						}
					},

					{
						//new record form
						closeAfterAdd: true,
						recreateForm: true,
						viewPagerButtons: false,
						beforeShowForm : function(e) {
							var form = $(e[0]);
							form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
							style_edit_form(form);
						},
						afterComplete: function(e) {
							alert("增加成功!");
							location.reload();
						}
					},

					{
						//delete record form
						recreateForm: true,
						beforeShowForm : function(e) {
							var form = $(e[0]);
							if(form.data('styled')) return false;
							
							form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
							style_delete_form(form);
							
							form.data('styled', true);
						},
						onClick : function(e) {
							alert(1);
						},
						afterComplete: function(e) {
							alert("删除成功!");
							location.reload();
						}
					},

					{
						//search form
						recreateForm: true,
						afterShowSearch: function(e){
							var form = $(e[0]);
							form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
							style_search_form(form);
						},
						
						afterRedraw: function(){
							style_search_filters($(this));
						}
						,
						multipleSearch: true,
						/**
						multipleGroup:true,
						showQuery: true
						*/
					},

					{
						//view record form
						recreateForm: true,
						beforeShowForm: function(e){
							var form = $(e[0]);
							form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
						}
					}
				).navSeparatorAdd(pager_selector,				//navSeparatorAdd是增加一个|进行按钮分割.
						{sepclass : "ui-separator",sepcontent: ''}
				).navButtonAdd(pager_selector,{
					/**************
						caption:按钮名称,可以为空,string类型 
						buttonicon:按钮的图标,string类型,必须为UI theme图标 
						onClickButton:按钮事件,function类型,默认null 
						position:first或者last,按钮位置 
						title:string类型,按钮的提示信息 
						cursor:string类型,光标类型,默认为pointer 
						id:string类型,按钮id
					*********************/
					//绑定合同号按钮	
					caption:"",
					title:"绑定合同", 
					buttonicon : 'icon-cogs purple',
					onClickButton: function()
					{
						var id = $("#grid-table").jqGrid('getGridParam', 'selrow');
						if (id == null){
							alert("请选择一条记录");
						} else {
							bindAttachment(id);
						}
					}
				}).navButtonAdd(pager_selector,{
					//上传文件按钮	
					caption:"",
					title:"上传计划单",
					buttonicon : 'icon-cloud-upload blue',
					onClickButton: function()
					{
						var id = $("#grid-table").jqGrid('getGridParam', 'selrow');
						if (id == null){
							alert("请选择一条记录");
						} else {
							uploadAttachment(id);
						}
					}
				})					
			
				function style_edit_form(form) {
					//enable datepicker on "sdate" field and switches for "stock" field
					form.find('input[name=sdate]').datepicker({format:'yyyy-mm-dd' , autoclose:true})
						.end().find('input[name=stock]')
							  .addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');
			
					//update buttons classes
					var buttons = form.next().find('.EditButton .fm-button');
					buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon
					buttons.eq(0).addClass('btn-primary').prepend('<i class="icon-ok"></i>');
					buttons.eq(1).prepend('<i class="icon-remove"></i>')
					
					buttons = form.next().find('.navButton a');
					buttons.find('.ui-icon').remove();
					buttons.eq(0).append('<i class="icon-chevron-left"></i>');
					buttons.eq(1).append('<i class="icon-chevron-right"></i>');		
				}
			
				function style_delete_form(form) {
					var buttons = form.next().find('.EditButton .fm-button');
					buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon
					buttons.eq(0).addClass('btn-danger').prepend('<i class="icon-trash"></i>');
					buttons.eq(1).prepend('<i class="icon-remove"></i>')
				}
				
				function style_search_filters(form) {
					form.find('.delete-rule').val('X');
					form.find('.add-rule').addClass('btn btn-xs btn-primary');
					form.find('.add-group').addClass('btn btn-xs btn-success');
					form.find('.delete-group').addClass('btn btn-xs btn-danger');
				}

				function style_search_form(form) {
					var dialog = form.closest('.ui-jqdialog');
					var buttons = dialog.find('.EditTable')
					buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'icon-retweet');
					buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'icon-comment-alt');
					buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'icon-search');
				}
				
				function beforeDeleteCallback(e) {
					var form = $(e[0]);
					if(form.data('styled')) return false;					
					form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
					style_delete_form(form);				
					form.data('styled', true);
				}
				
				function beforeEditCallback(e) {
					var form = $(e[0]);
					form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
					style_edit_form(form);
				}
									
				//it causes some flicker when reloading or navigating grid
				//it may be possible to have some custom formatter to do this as the grid is being created to prevent this
				//or go back to default browser checkbox styles for the grid
				function styleCheckbox(table) {
				/**
					$(table).find('input:checkbox').addClass('ace')
					.wrap('<label />')
					.after('<span class="lbl align-top" />')					
					$('.ui-jqgrid-labels th[id*="_cb"]:first-child')
					.find('input.cbox[type=checkbox]').addClass('ace')
					.wrap('<label />').after('<span class="lbl align-top" />');
				*/
				}
							
				//unlike navButtons icons, action icons in rows seem to be hard-coded
				//you can change them like this in here if you want
				function updateActionIcons(table) {
					/**
					var replacement = 
					{
						'ui-icon-pencil' : 'icon-pencil blue',
						'ui-icon-trash' : 'icon-trash red',
						'ui-icon-disk' : 'icon-ok green',
						'ui-icon-cancel' : 'icon-remove red'
					};

					$(table).find('.ui-pg-div span.ui-icon').each(function(){
						var icon = $(this);
						var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
						if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
					})
					*/
				}
				
				//replace icons with FontAwesome icons like above
				function updatePagerIcons(table) {
					var replacement = 
					{
						'ui-icon-seek-first' : 'icon-double-angle-left bigger-140',
						'ui-icon-seek-prev' : 'icon-angle-left bigger-140',
						'ui-icon-seek-next' : 'icon-angle-right bigger-140',
						'ui-icon-seek-end' : 'icon-double-angle-right bigger-140'
					};

					$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
						var icon = $(this);
						var $class = $.trim(icon.attr('class').replace('ui-icon', ''));						
						if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
					})
				}
		
				function enableTooltips(table) {
					$('.navtable .ui-pg-button').tooltip({container:'body'});
					$(table).find('.ui-pg-div').tooltip({container:'body'});
				}			
				//var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');						
			});
		</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值