Я использую jqGrid на своей странице и использую jqTree (https://mbraak.github.io) для свойства Division. В форме поиска свойства я создаю элемент jqTree в этой функции:
var divisionTreeInit = function(elem) {
console.log("divisionTreeInit");
var tmp=$(el).tree({
data: divisionTreeJSON,
autoOpen: 0,
});
$(el).on(
'tree.click',
function(event) {
console.log(event.node.id);
$(elem).val(event.node.id);
}
);
$(elem).parent().append(tmp);
//$(elem).val("7");
return elem;
};
и подписываю эту функцию в модели jqGrid
colModel:[
....
{name:'division',index:'division',width:180, hidden:false,editable:true,formatter:divisionNameFormatter, edittype:'custom',editoptions: {size:100,custom_element: myelem, custom_value:myvalue},editrules:{edithidden:true,required:true},stype:"text",searchoptions:{sopt:['eq','ne'],dataInit:divisionTreeInit,}, searchrules:{required:true} },
Итак, у меня есть Форма поиска, Когда я вручную набираю код деления на поле ввода, он работает нормально. Но когда я выбираю Division из jqTree (и значение кода отображается в поле ввода), поиск не работает. Похоже, jqGrid не может видеть значение в поле ввода.
Может, кто-нибудь скажет мне, почему так?
Полный код моей страницы
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<link rel="stylesheet" href="<c:url value="/css/mbraak-jqTree/jqtree.css" />">
<script src="<c:url value="/js/mbraak-jqTree/tree.jquery.debug.js" />"></script>
<script type="text/javascript">
$(document).ready(function(){
var el = document.createElement("div"); el.id="tree"; //элемент, куда добавляем division
var getDivisionTreeJSON = function() { //получаем с сервера division json
var request = $.ajax({
type: 'GET',
async:false,
url: '${curUrl}hardwareItem/divisionTreeNew',
});
var tree="";
request.done(function(resp){
tree=resp;
});
return tree;
};
var divisionTreeJSON = getDivisionTreeJSON();
var selectedDivision=""; //храним выделеный division
/*var hardwareTypeList = new Array();
<c:forEach items="${hardwareTypeList}" var="s">
hardware = new Object();
hardware.name = "${s.name}";
hardwareTypeList["${s.id}"]=hardware;
</c:forEach>
var prepareList = function(list) { //преобразует
let newObject={};
for (let key in list) {
newObject[key]=list[key].name;
}
return newObject;
}
var shortHardwareTypeList=prepareList(hardwareTypeList);*/
var shortHardwareTypeList = new Object();
<c:forEach items="${hardwareTypeList}" var="s">
//hardware = new Object();
//hardware.name = "${s.name}";
shortHardwareTypeList["${s.id}"]="${s.name}";
</c:forEach>
//Собственная обработка ошибки
var originalCheckValues = $.jgrid.checkValues;
$.jgrid.checkValues = function(val, valref,g, customobject, nam) {
var ret = originalCheckValues.call(this,val, valref,g, customobject, nam);
if (!ret[0]) {
$("tr#tr_"+valref+" td.CaptionTD").addClass("ui-state-error");
} else {
$("tr#tr_"+valref+" td.CaptionTD").removeClass("ui-state-error");
}
return ret;
};
var dateFormat=$.datepicker.regional[mylocale()].dateFormat;
var dateFormatter=function(cellvalue, options, rowObject) {
return $.datepicker.formatDate(dateFormat,new Date(cellvalue));
};
var checkDate=function(value, colname){
try {
$.datepicker.parseDate(dateFormat,value);
} catch(e) {
return [false,colname+', ' + dateFormat];
}
return [true,""];
/* var a=value.match(/(\d{1,2})\.(\d{1,2})\.(\d{2,4})/);
if (a==null) {
return [false,colname+" должна быть в формате DD.MM.YYYY"];
}
return [true,""]; */
};
var datePick = function(elem) {
jQuery(elem).datepicker();
};
var divisionTreeInit = function(elem) {
console.log("divisionTreeInit");
var tmp=$(el).tree({
data: divisionTreeJSON,
autoOpen: 0,
});
$(el).on(
'tree.click',
function(event) {
console.log(event.node.id);
$(elem).val(event.node.id);
}
);
$(elem).parent().append(tmp);
//$(elem).val("7");
return elem;
};
var myelem = function(value, options) {
console.log("myelem value:"+value);
selectedDivision="";
var tmp=$("#photos").getRowData(options.rowId).division;
var division = tmp.split(":")[0];
var divisionTree = $(el).tree({
data: divisionTreeJSON,
autoOpen: 0,
//dragAndDrop: false,
//selectable: true,
onCanSelectNode: function(node) {
if (node.children.length == 0) {
return true;
}
else {
return false;
}
}
});
divisionTree.on(
'tree.click',
function(event) {
selectedDivision = event.node.id;
}
);
var node = divisionTree.tree('getNodeById',division);
divisionTree.tree('selectNode', node);
return el;
}
var myvalue = function(elem, operation, value) {
console.log("myvalue operation:"+operation+", value:"+value)
if(operation === 'get') {
return String(selectedDivision);
}
}
var hardwareTypeOptions = {
size:1,
value:shortHardwareTypeList,
sopt:['eq','ne'],
};
var hardwareTypeFormatter = function(cellvalue, options, rowObject ){
return cellvalue.name;
}
var ipAddrFormatter = function(cellvalue, options, rowObject ){
return cellvalue.ipStr;
}
var divisionFormatter = function(cellvalue, options, rowObject ){
console.log("divisionFormatter");
return cellvalue.id;
}
var divisionNameFormatter = function(cellvalue, options, rowObject ){
//console.log("divisionNameFormatter");
//console.log(cellvalue);
return cellvalue.id+":"+cellvalue.name;
}
var ipAddrInit=function(elem) {
//console.log(elem);
$(elem).mask('0ZZ.0ZZ.0ZZ.0ZZ', {
translation: {
'Z': {
pattern: /[0-9]/, optional: true
}
}
});
};
$("#photos").jqGrid({
height:"auto",
autowidth:true,
shrinkToFit:true,
styleUI : "Bootstrap",
url:url("/dataDirectory/hardwareItem/crud"),
datatype: "json",
loadError: function (jqXHR, textStatus, errorThrown) {
console.log("loadError");
},
colNames:[
'<spring:message code="Domain.HardwareItem.id"/>',
'<spring:message code="Domain.HardwareItem.HardwareType"/>',
'<spring:message code="Domain.HardwareItem.InventoryNumber"/>',
'<spring:message code="Domain.HardwareItem.EntryDate"/>',
'<spring:message code="Domain.HardwareItem.IpAddr"/>',
'<spring:message code="Domain.HardwareItem.Description"/>',
'<spring:message code="Domain.HardwareItem.Division"/>',
],
colModel:[
{name:'id',index:'id', width:50,key:true,search:false,editable:false, editoptions: { size: 10, readonly: 'readonly'}},
{name:'hardwareType',width:180,index:'hardwareType', editable:true, edittype:'select',editoptions: hardwareTypeOptions ,stype:'select', searchoptions: hardwareTypeOptions, searchrules:{required:true},formatter: hardwareTypeFormatter,},
{name:'inventoryNumber',index:'inventoryNumber',width:180, editable:true, edittype:'text',editoptions: {size:100,}, searchrules:{required:true} },
{name:'entryDate',index:'entryDate', width:80,editable: true,edittype: 'text',editoptions:{ dataInit :datePick}, formatter:dateFormatter,/* unformat:dateUnformatter,*/editrules:{custom:true,custom_func:checkDate},stype:"text",searchoptions:{ dataInit :datePick,sopt:['eq','ne','lt','le','gt','ge']},searchrules:{required:true,custom:true,custom_func:checkDate} },
{name:'ipAddr',index:'ipAddr',width:180, editable:true, edittype:'text',editoptions: {size:100}, searchrules:{required:true},searchoptions:{sopt:['eq','ne','lt','le','gt','ge'],dataInit:ipAddrInit},formatter: ipAddrFormatter,},
{name:'description',index:'description',width:180, editable:true, edittype:'text',editoptions: {size:100}, searchrules:{required:true} },
{name:'division',index:'division',width:180, hidden:false,editable:true,formatter:divisionNameFormatter, edittype:'custom',editoptions: {size:100,custom_element: myelem, custom_value:myvalue},editrules:{edithidden:true,required:true},stype:"text",searchoptions:{sopt:['eq','ne'],dataInit:divisionTreeInit,}, searchrules:{required:true} },
],
jsonReader:{
id:'id'
},
rowNum:10,
loadonce: false,
rowList:[10,20,30],
pager: '#pager2',
sortname: 'id',
viewrecords: true,
toolbar:[true,"both"],
sortorder: "asc",
caption:'<spring:message code="Domain.HardwareItem"/>',
cellEdit : false,
editurl : url("/dataDirectory/hardwareItem/crud/do"),
});
var fn_formSubmit=function(response, postdata) {
var result = eval('(' + response.responseText + ')');
var errors = "";
if (!result.success) {
for (var i = 0; i < result.message.length; i++) {
var tmp=result.message[i].split(";");
errors += tmp[1]+"<br>";
$("tr#tr_"+tmp[0]+" td.CaptionTD").addClass("ui-state-error");
//$("tr#tr_"+tmp[0]+" td.DataTD input").addClass("is-invalid");
//console.log($("tr#tr_"+tmp[0]+" td.DataTD input"));
}
}
//console.log(response.responseText);
return [result.success,errors,null];
};
var beforeShowForm=function(form) {
//console.log(form);
//let id = $(form).find("select option:selected").val();
$("input[name='ipAddr'].FormElement.form-control").mask('0ZZ.0ZZ.0ZZ.0ZZ', {
translation: {
'Z': {
pattern: /[0-9]/, optional: true
}
}
});
};
var editOptions={top: 50, left: "100", width: 500,closeOnEscape: true,closeAfterEdit:true,viewPagerButtons:false,savekey:[true,13],navkeys:[false,38,40], afterSubmit: fn_formSubmit,beforeShowForm:beforeShowForm};
var addOptions={top: 50, left: "100", width: 500,closeOnEscape: true,closeAfterAdd:true, afterSubmit: fn_formSubmit,beforeShowForm:beforeShowForm};
var delOptions={};
var searchOptions={top: 50, left: "100", width: 500,closeOnEscape: true,closeAfterAdd:true, afterSubmit: fn_formSubmit,sopt:['eq','ne','bw','ew','cn'] };
$("#photos").jqGrid('navGrid','#pager2',{edit:true,add:true,del:true,search:true,view:false,refresh:false},editOptions,addOptions,delOptions,searchOptions);
});
</script>
<table id="photos" class="display" cellspacing="0" width="100%">
</table>
<div id="pager2"></div>