aoData is null when using multiple instances of jquery datatable - javascript

Scenario:
On a webpage I have three divs that contain table tags.
There are 3 buttons, clicking on each button creates an instance of the datatable on a particular div with the table tag.
The datatable gets the data from serverside
All the data returned and displayed, pagination, filtering works fine.
So when all three instances are created, using fnSettings() on only the last instance created returns the proper object, and the other two instances return null
So using fnData() etc api methods throw an error saying : "TypeError: Cannot read property 'aoData' of null" because settings object of that datatable instance is somehow null
Code Description
I have made a class called datagrid, and I create multiple instances of this class:
/**
* datagrid class contains methods and properties that will help in controllling and manipulating the multiple instances of the datagrid class
*
* This function is the constructor for the datagrid class
*
* #param {string} domContainerSelector DOM selector of the element containing the datagrid
* #param {Array} columns Definitions of the columns of the datagrid
* #param {string} ajaxSource The url that the jqgrid will use to request for data
* #param {Object} configurationParameters The configuration parameters that will be used by the jqGrid and this datagrid instance. Currently suppoted configuration parameters are: initialCacheSize, iDisplayLength, sScrollY, bPaginate, bFilter, sDom, bSort
* #param {Object} uiCallback Contains callback functions that are used when a server request is in progress and after the completion of the request. Mainly used for showing progress indicators.
* #returns {datagrid}
*/
function datagrid(domContainerSelector, columns, ajaxSource, configurationParameters, uiCallback)
{
this.domContainerSelector = domContainerSelector;
this.domTableSelector = this.domContainerSelector + " #grid";
this.domRowSelector = this.domTableSelector + " tbody tr";
this.domGridWrapperSelector = this.domContainerSelector + " .dataTables_wrapper";
this.columns = columns;
this.ajaxSource = ajaxSource;
this.configParams = configurationParameters;
this.uiCallback = uiCallback;
this.cache= {
start: 0,
end: 0,
initialSize:this.configParams.initialCacheSize == undefined ? 2 : this.configParams.initialCacheSize,
pageSize:this.configParams.iDisplayLength == undefined ? 10 : this.configParams.iDisplayLength,
loading:false,
jsondata: {},
reset: function(){
this.start=0;
this.end=0;
this.loading=false;
this.jsondata={};
}
};
/**
* This method returns the row selected by the user
*
* #return {Object} Row object containing columns as its properties
*/
this.getSelectedRow = function()
{
var allrows = this.dataTable.fnGetNodes();
for (i = 0; i < allrows.length; i++)
if ($(allrows[i]).hasClass('row_selected'))
return this.dataTable.fnGetData(allrows[i]);
};
this.getPostDataValue=function(postData, key){
for (var i=0;i<postData.length;i++)
{
if (postData[i].name == key)
{
return postData[i].value;
}
}
return null;
};
this.setPostDataValue=function(postData, key, value){
for (var i=0; i<postData.length;i++)
{
if (postData[i].name == key)
{
postData[i].value = value;
}
}
};
this.setPostDataFilterValues=function(postData){
for (i=0;i<this.columns.length;i++)
{
var key="sSearch_"+i;
this.setPostDataValue(postData,key,this.columns[i].sSearch===undefined?'':this.columns[i].sSearch);
}
};
this.filterColumnKeyupHandler = function(evt) {
var id=evt.target.id;
var index=id.charAt(id.length-1);
var oldvalue=this.columns[index].sSearch;
var value = evt.target.value == '' ? undefined : evt.target.value;
if (oldvalue!=value) this.cache.reset();//resetting the cache because the datagrid is in dirty state
this.columns[index].sSearch=value;
if (evt.keyCode == 13) this.dataTable.fnFilter();
};
/**
* This method acts as the general button handler when an operation is in progress
*/
this.busyStateButtonHandler=function()
{
ui.showmessage("Another operation is in progress. Please wait for the operation to complete");
};
/**
* This method sets the event handlers for the datagrid
*/
this.setEventHandlers = function() {
var self=this;
$(this.domGridWrapperSelector + " input[class='columnfilterinput']").off("keyup").on("keyup", function(evt) {self.filterColumnKeyupHandler(evt,self)});
$(this.domGridWrapperSelector + " .filterbar .searchbtn").off("click").on("click", function() {self.dataTable.fnFilter()});
};
/**
* This method sets the appropriate event handlers to indicate busy status
*/
this.setBusyStatusEventHandlers=function()
{
$(this.domGridWrapperSelector + " input[class='columnfilterinput']").off("keyup").on("keyup", this.busyStateButtonHandler);
$(this.domGridWrapperSelector + " .filterbar .searchbtn").off("click").on("click", this.busyStateButtonHandler);
};
/**
* This method enables column specific filtering
*
* This methods adds filtering capability to columns whose definitions indicate that they are searchable (bSearchable:true)
*/
this.enablecolumnfilter = function() {
var self = this;
var oTable = self.dataTable;
var oSettings = oTable.fnSettings();
var aoColumns = oSettings.aoColumns;
var nTHead = oSettings.nTHead;
var htmlTrTemplate = "<tr class='filterbar'>{content}</tr>";
var htmlTdTemplate = "<td>{content}</td>";
var htmlInputTemplate = "<input type='text' name='{name}' id='{id}' class='{class}' /><div class='searchbtn' id='{searchbtnid}'><div class='icon-filter'></div></div>";
var isAnyColumnFilterable = false;
var htmlTr = htmlTrTemplate;
var allHtmlTds = "";
for (i = 0; i < aoColumns.length; i++)
{
var column = aoColumns[i];
var htmlTd = htmlTdTemplate;
if (column.bSearchable == true)
{
isAnyColumnFilterable = true;
var htmlInput = htmlInputTemplate;
htmlInput = htmlInput.replace('{name}', column.mData);
htmlInput = htmlInput.replace('{id}', "sSearch_" + i);
htmlInput = htmlInput.replace('{class}', 'columnfilterinput');
htmlTd = htmlTd.replace('{content}', htmlInput);
}
else
htmlTd = htmlTd.replace('{content}', '');
allHtmlTds += htmlTd;
}
if (isAnyColumnFilterable)
{
htmlTr = htmlTr.replace('{content}', allHtmlTds);
nTHead.innerHTML += htmlTr;
$(this.domGridWrapperSelector + " .filterbar input[class='columnfilterinput']").each(function(){
$(this).width($(this).parent().width()-26);
});
}
};
/**
* This method enables single selection on the rows of the grid
*/
this.enableSelection = function()
{
$(this.domRowSelector).die("click").live("click", function() {
if ($(this).hasClass('row_selected')) {
$(this).removeClass('row_selected');
}
else {
$(this).siblings().removeClass('row_selected');
$(this).addClass('row_selected');
}
});
};
this.loadDataIntoCache=function(postData, sourceUrl, start, length){
if (!this.cache.loading)
{
var postData=$.extend(true, [], postData);
var start = start==undefined?this.cache.end:start;
var length = length==undefined?this.cache.pageSize:length;
var end = start + length;
this.setPostDataValue(postData, "iDisplayStart", start);
this.setPostDataValue(postData, "iDisplayLength", length);
var self=this;
this.cache.loading=true;
$.ajax({
type: "POST",
url: sourceUrl,
data: postData,
success:
function(json, textStatus, jqXHR)
{
json = JSON.parse(json);
var olddata=self.cache.jsondata.aaData;
if (olddata===undefined) self.cache.jsondata = $.extend(true, {}, json);
else olddata.push.apply(olddata,json.aaData);
self.cache.end=end;
},
error:
function(jqXHR, textStatus, errorThrown)
{
ui.showmessage(jqXHR.responseText);//remove this from here
},
complete:
function()
{
self.cache.loading=false;
}
});
}
};
this.loadDataFromCache=function(postData,sourceUrl){
var start=this.getPostDataValue(postData, "iDisplayStart");
var length=this.cache.pageSize;
var end=start+length;
var sEcho = this.getPostDataValue(postData,"sEcho");
if (this.cache.end>=end)
{
var jsondata=$.extend(true, {},this.cache.jsondata);
var data=jsondata.aaData;
jsondata.aaData=data.splice(start,length);
jsondata.sEcho = sEcho;
var totalRecords=jsondata.iTotalRecords;
if ((this.cache.end-end)<((this.cache.initialSize*this.cache.pageSize)/2) && (totalRecords==0 || this.cache.end<totalRecords) ) this.loadDataIntoCache(postData, sourceUrl);//prefetch data if needed
return jsondata;
}
else
{
this.loadDataIntoCache(postData,sourceUrl);
return null;
}
};
/**
* This method interfaces with the backend end controller
*
* This method is called when the grid initiates any operation that requires server side processing
*
* #param {String} sSource The source url that will be used for the xhr request
* #param {Array} aoData Contains the parameters sent by the dataTable that will be forwarded to the backend controller
* #param {Function} fnCallback The callback function of the dataTable that gets executed to finally render the grid with the data
*/
this.interfaceWithServer = function(sSource, aoData, fnCallback)
{
this.setPostDataFilterValues(aoData);
var self=this;
if (this.cache.end==0)
{
this.setPostDataValue(aoData, "iDisplayStart", this.cache.start);
if (this.dataTable!=undefined) this.dataTable.fnSettings()._iDisplayStart=0;
this.loadDataIntoCache(aoData, sSource, 0, (this.cache.initialSize*this.cache.pageSize));
}
var data=this.loadDataFromCache(aoData,sSource);
if (data!=null) fnCallback(data);
else
{
this.setBusyStatusEventHandlers();
this.uiCallback.inprogress();
self.cacheLoadingTimerId=setInterval(function(){
if (self.cache.loading==false)
{
clearInterval(self.cacheLoadingTimerId);
var data=self.loadDataFromCache(aoData,sSource);
fnCallback(data);
self.uiCallback.completed();
self.setEventHandlers();
}
},500);
}
};
/**
* This method destroys the datatable instance
*
* Remove all the contents from the parent div and reinserts a simple table tag on which a fresh datatable will be reinitialized
*/
this.destroy = function()
{
$(this.domRowSelector).die("click");
$(this.domGridWrapperSelector).remove();//remove only the datatable generated dynamic code
$(this.domContainerSelector).prepend("<table id='grid'></table>");
};
/**
* The dataTable property holds the instance of the jquery Datatable
*/
this.dataTable = $(this.domTableSelector).dataTable({
"bJQueryUI": true,
"sScrollY": this.configParams.sScrollY == undefined ? "320px" : this.configParams.sScrollY,
"bAutoWidth": true,
"bPaginate": this.configParams.bPaginate == undefined ? true : this.configParams.bPaginate,
"sPaginationType": "two_button",
"bLengthChange": false,
"bFilter": this.configParams.bFilter == undefined ? true : this.configParams.bFilter,
"sDom": this.configParams.sDom == undefined ? '<"H"lfr>t<"F"ip>' : this.configParams.sDom,
"bSort": this.configParams.bSort == undefined ? true : this.configParams.bSort,
"iDisplayLength": this.configParams.iDisplayLength == undefined ? 10 : this.configParams.iDisplayLength,
"bServerSide": true,
"sAjaxSource": this.ajaxSource,
"fnServerData": this.interfaceWithServer.bind(this),
"oLanguage": {
"sZeroRecords": "No Records Found",
"sInfo": "_START_ - _END_ of _TOTAL_",
"sInfoEmpty": "0 to 0 of 0"
},
"aoColumns": this.columns
});
this.init=function(){
this.enableSelection();
this.enablecolumnfilter();
this.setEventHandlers();
};
this.init();
};
Now in my web page this is where I create the 3 instances :
switch (dialog)
{
case "cusgrp_dialog":
var columndefs = [
{
"sTitle": "XWBNCD",
"mData": "xwbncd",
"sWidth": "40%"
},
{
"sTitle": "XWKHTX",
"mData": "xwkhtx",
"sWidth": "60%"
}
];
var ajaxSource = "./entities/Cusgrp";
var configurationParameters = {
bFilter: null,
sDom: 't<"dataTable_controlbar"ip>'
};
this.customergroupDatagrid = new datagrid(domContainerSelector, columndefs, ajaxSource, configurationParameters, uiCallback);
break;
case "slmen_dialog":
var columndefs = [
{
"sTitle": "PERSON",
"mData": "person",
"sWidth": "40%"
},
{
"sTitle": "PNAME",
"mData": "pname",
"sWidth": "60%"
}
];
var ajaxSource = "./entities/Slmen";
var configurationParameters = {
bFilter: null,
sDom: 't<"dataTable_controlbar"ip>'
};
this.salesmanDatagrid = new datagrid(domContainerSelector, columndefs, ajaxSource, configurationParameters, uiCallback);
break;
case "dists_dialog":
var columndefs = [
{
"sTitle": "DSDCDE",
"mData": "dsdcde",
"sWidth": "40%"
},
{
"sTitle": "DNAME",
"mData": "dname",
"sWidth": "60%"
}
];
var ajaxSource = "./entities/Dists";
var configurationParameters = {
bFilter: null,
sDom: 't<"dataTable_controlbar"ip>'
};
this.distributorDatagrid = new datagrid(domContainerSelector, columndefs, ajaxSource, configurationParameters, uiCallback);
break;
}
After all three instances are created, only the last one supposedly has fnSettings() object defined rest instances return null for fnSettings and thus calling other api methods that use aoData (which is a member of the fnSettings() returned object) show the error that can't read property aoData of null
Console Preview:
The 3 instances are stored in customergroupDatagrid, salesmanDatagrid, distributorDatagrid variables
When the customergroupDatagrid instance is created
customergroupDatagrid.dataTable.fnSettings(); // returns object
When the salesmanDatagrid instance is created
salesmanDatagrid.dataTable.fnSettings(); // returns object
customergroupDatagrid.dataTable.fnSettings(); // returns null
When the distributorDatagrid instance is created
distributorDatagrid.dataTable.fnSettings(); // returns object
salesmanDatagrid.dataTable.fnSettings(); // returns null
customergroupDatagrid.dataTable.fnSettings(); // returns null

I believe the problem is that your tables all have the same ID. Please note proper HTML requires unique IDs:
http://www.w3.org/TR/html401/struct/global.html#h-7.5.2
id = name [CS]
This attribute assigns a name to an element. This name
must be unique in a document.
Here are two jsfiddles.
http://jsfiddle.net/QFrz9/
var dt1 = $('#div1 #grid').dataTable();
alert('dt1 settings: ' + dt1.fnSettings());
var dt2 = $('#div2 #grid').dataTable();
alert('dt1 settings: ' + dt1.fnSettings());
alert('dt2 settings: ' + dt2.fnSettings());
http://jsfiddle.net/mRFaP/1/
var dt1 = $('#div1 #grid1').dataTable();
alert('dt1 settings: ' + dt1.fnSettings());
var dt2 = $('#div2 #grid2').dataTable();
alert('dt1 settings: ' + dt1.fnSettings());
alert('dt2 settings: ' + dt2.fnSettings());
The first one duplicates your code, using the same id for the two tables. It displays an alert after the first table is created; fnSettings is not null. Then it displays an alert after the next table is created, and suddenly the fnSettings of table 1 is null. The second jsfiddle uses unique ids, and the problem disappears.
Perhaps your table id could be a combination of the div ID and "grid", e.g., div1grid, div2grid etc. Then you would use domContainerSelector + 'grid' instead of ' #grid'.

Related

Trying to access a sublist in Netsuite with suitescript

I am trying to access a sublist in NetSuite with a workflow script. I placed a button on all sales orders that once pressed will execute this script. I keep getting an error that my sublist is null. If it is null can someone explain why?
function(record) {
var salesorder = record.newRecord;
var salesordernumber = salesorder.getValue('tranid');
var date = salesorder.getValue('trandate');
var sublist = salesorder.getSublistValue({
Sublistid : 'item'
});
log.debug('Employee Code', salesordernumber);
log.debug('Supervisior Name', date);
log.debug('itemr', sublist);
/**
* Definition of the Suitelet script trigger point.
*
* #param {Object} scriptContext
* #param {Record} scriptContext.newRecord - New record
* #param {Record} scriptContext.oldRecord - Old record
* #Since 2016.1
*/
});
function onAction(context) {
return {
onAction : onAction
};
}
//Load created Sales Order so that we can fetch data
var salesObjRecord = record.load({
type: record.Type.SALES_ORDER,
id: salesOrderID,
isDynamic: true
});
var itemDetailsObj = new Object();
var numLines = salesObjRecord.getLineCount({
sublistId : 'item'
}); // to get sublist line number
if (numLines > 0) {
for (var i = 0; i < numLines; i++) {
itemDetailsObj.amount = salesObjRecord.getSublistValue({
sublistId : 'item',
fieldId : 'amount',
line : i
});
itemDetailsObj.rate = salesObjRecord.getSublistValue({
sublistId : 'item',
fieldId : 'rate',
line : i
});
itemDetailsObj.quantity = salesObjRecord.getSublistValue({
sublistId : 'item',
fieldId : 'quantity',
line : i
});
}
}
record.getSublistValue() returns the value of a sublist field. A sublist field is uniquely identified by 3 parameters:
sublistId
fieldId
line
All these parameters are required, but your code is not providing all of them.

Multiple onblur elements gives error

I am try to call a function onblur of my three elements in my table
but i am getting this error in my console
"((m.event.special[e.origType] || (intermediate value)).handle || e.handler).apply is not a function".
So onblur these elements i want to call my function.Please do have a look at my code once.
Apologies for my bad handwriting here .I am new to javascript
jq.ajax({
url: '/soap/ajax/36.0/connection.js',
dataType: 'script',
success: function() {
jq(document).ready(function() {
// call tookit dependent logic here
jq('#gbMainTable').on('blur', 'tr.dr td[name="v4"] select','tr.dr td[name="v6"] select','tr.dr td[name="v7"] input', function()
{
var thisInput = this;
console.log('thisInput.value',thisInput.value);
var thisInput1 = jq(this);
var thisRow = thisInput1.parents('tr.dr:first');
console.log('thisRow',thisRow);
var agentInput1 = thisRow.find('td:eq(7)');
console.log('agentInput1',agentInput1);
var finds1 = agentInput1.find('select');
console.log('finds1',finds1);
var agentInput2 = thisRow.find('td:eq(8)');
console.log('agentInput2',agentInput2);
var finds2= agentInput2.find('input');
if(agentInput1.text()!=='' & thisInput.value=='Programmable Cntrls/Welders/AC Drives/Soft Starts'){
exampleFunction('Programmable',agentInput1.text(),agentInput2.text());
console.log('YES');
}
else if(agentInput1.text()!=='' & thisInput.value=='Electro Mechanical'){
exampleFunction('Electro-Mechanical',agentInput1.text(),agentInput2.text());
}
});
});
},
async: false
});
function exampleFunction(Warranty,Years,charge) {
var state = { // state that you need when the callback is called
output : null,
startTime : new Date().getTime()};
var callback = {
//call layoutResult if the request is successful
onSuccess: doThis,
//call queryFailed if the api request fails
onFailure: queryFailed,
source: state};
sforce.connection.query(
"SELECT InOut__c,PlantPct__c,T37Pct__c,TotalPct__c,Type__c,Warranty_Code__c,Years__c FROM WarrantySpecialLine__c where InOut__c = '" +charge+"' and Years__c = '"+Years+"' and Type__c = '" +Warranty +"'",
callback);
}
function queryFailed(error, source) {
console.log('error: '+error);
}
/**
* This method will be called when the toolkit receives a successful
* response from the server.
* #queryResult - result that server returned
* #source - state passed into the query method call.
*/
function doThis(queryResult, source) {
if (queryResult.size > 0) {
var output = "";
// get the records array
var records = queryResult.getArray('records');
// loop through the records
for (var i = 0; i < records.length; i++) {
var warrantySpecial = records[i];
console.log(warrantySpecial.PlantPct__c + " " + warrantySpecial.TotalPct__c + " " +warrantySpecial.T37Pct__c );
}
}
}

jQuery - code repetition

I am absolute begginer in jQuery. I wrote some code for my app and put it into .js file:
How should I avoid code repetition in jQuery? Where should I store my .js code (one huge .js file, couple of smaller or straight in html source)?
This is my .js file:
$(document).ready(function() {
$("label[for='id_category1'], #id_category1, label[for='id_subcategory1'],#id_subcategory1 ").hide();
$('select[name=subcategory]').empty();
$('select[name=subcategory]').prepend('<option value="Not selected" selected disabled>Select Category...</option>');
$('select[name=subcategory1]').empty();
$('select[name=subcategory1]').prepend('<option value="Not selected" selected disabled>Select Category...</option>');
// called when category field changes from initial value
$('#id_group').change(function() {
var $this = $(this);
if ($this.find('option:selected').attr('value') == 'premium') {
$("label[for='id_category1'], #id_category1").show();
$("label[for='id_subcategory1'], #id_subcategory1").show();
} else {
$("label[for='id_category1'], #id_category1").hide();
$("label[for='id_subcategory1'], #id_subcategory1").hide();
}
})
$('#id_category').change(function() {
var $this = $(this);
if ($this.find('option:selected').index() !== 0) {
category_id = $('select[name=category]').val();
request_url = '/get_subcategory/' + category_id + '/';
$.ajax({
url: request_url,
type: "GET",
success: function(data) {
$('select[name=subcategory]').empty();
$.each(data, function(key, value) {
$('select[name=subcategory]').append('<option value="' + key + '">' + value + '</option>');
});
}
})
}
})
$('#id_category1').change(function() {
var $this = $(this);
if ($this.find('option:selected').index() !== 0) {
category_id = $('select[name=category1]').val();
request_url = '/get_subcategory/' + category_id + '/';
$.ajax({
url: request_url,
type: "GET",
success: function(data) {
$('select[name=subcategory1]').empty();
$.each(data, function(key, value) {
$('select[name=subcategory1]').append('<option value="' + key + '">' + value + '</option>');
});
}
})
}
})
$("label[for='id_keywords']").html("Keywords 0/100");
$('#id_keywords').keyup(function() {
var charsno = $(this).val().length;
$("label[for='id_keywords']").html("Keywords (" + charsno + "/100)");
});
$("label[for='id_description']").html("Description 0/250");
$('#id_description').keyup(function() {
var charsno = $(this).val().length;
$("label[for='id_description']").html("Description (" + charsno + "/2500)");
});
});
Thank you for any clues to beginner.
ALWAYS separate javascript from HTML.
ALWAYS separate and load separate javascript files according to separate functionality.
Then try and break down into MVC type architecture. I've been there where a javascript file is 2000 lines long - its unmanageable for editing and debugging.
ALWAYS try and use classes.
Class architecture is pseudo in Javascript but:
var view;
var model;
var ctrl;
/** - js_include_mvc.js
* as per:
* http://stackoverflow.com/questions/15192722/javascript-extending-class
* provides the bare minimum facility to instantiate MVC objects if the base mvc classes are not subclassed
* this ensures there is always js mvc
*
*/
Ctrl.inherits(BaseCtrl);
function Ctrl(args) {
BaseCtrl.apply(this, arguments);
Ctrl.prototype.boot = function () {
}
}
View.inherits(BaseView);
function View(args) {
BaseView.apply(this, arguments);
View.prototype.boot = function () {
}
}
Model.inherits(BaseModel);
function Model(args) {
BaseModel.apply(this, arguments);
Model.prototype.boot = function () {
}
}
Then for example:
function BaseView() {
BaseView.prototype.somemethod = function () {
//some functionality here
return "I am a View";
}
}
And finally call it in the global page script:
var view=new BaseView();
view.somemethod();
outputs:
"I am a view"
I term the class BaseView as I put code that is always reused here, however the BaseView class can be further extended according to application. So BaseView is used a a main repository for all my apps and I extend it according to requirements.
Some of my code comments need a rewrite but my Ajax class goes like this:
if (SERVER_INTERFACES == undefined) {
var SERVER_INTERFACES = {};//global server array required for named multiple servers and asynch data callbacks
}
/** Ajax_js - communicates with the server to retrieve data
*
* #param String newName is the name this class can reference for things like callbacks
* #param Strin newUrl
* #param String newNamedServer is the resource url defined as a php ajax server class
* #returns {Ajax}
*/
function Ajax_m(newName, newUrl, newNamedServer) {
this.namedServer = newNamedServer;
this.interface_name = newName;
this.url = newUrl;
this.server_data; //allows a query to be given an id and the result data stored and accessible without having to manipulate into method arguments which might require data changes
this.server_data = new Array(); //allows a query to be given an id and the result data stored and accessible without having to manipulate into method arguments which might require data changes
this.request_index = 0;
this.multiqueryindex = 0;
this.multiqueryctrl = new Array();
this.dataType = "json";
this.reqType = "post";
SERVER_INTERFACES[this.interface_name] = this;
Ajax_m.prototype.request = function (requestobj, callback, optargs) {
optargs = model.array_defaults(optargs, {runtagvals: {}});
if (optargs.id == undefined) {
this.request_index++;
} else {
this.request_index = optargs.id;
}
var request_id = this.request_index;
if (typeof requestobj == "string") {
//legacy was the requestobj as a string which is set to request and defaults assumed
//attempt to parse ajaxRequestSubType as first 'word'
var clauseend = requestobj.indexOf(" ");
var ajaxRequestSubType = requestobj.substr(0, clauseend);
requestobj = {ajaxRequestSubType: ajaxRequestSubType, request: requestobj, callback: callback, request_id: request_id};
} else {
//for legacy if callback and id are defined they are added but if in requestobj they will be overridden
var args = {callback: callback, request_id: request_id};
for (var r in requestobj) {
args[r] = requestobj[r];
}
requestobj = args;
}
//ensure default settings
var requestbuild = model.array_defaults(
requestobj,
{
request: null,
callback: "",
errorCallback: null,
request_id: null,
interface_name: this.interface_name,
responsedata: null,
multirequestid: null,
ajaxRequestSubType: "",
ajaxRequestType: "database", //default to use database cfg definitions of site
ismultiparent: false,
_method: "PATCH"//for laravel5
}
);
requestbuild.request = model.runtagreplace(requestbuild.request, optargs.runtagvals);
this.server_data[request_id] = requestbuild;
//debug in chrome as firebug fucks up badly with switch control
switch (requestbuild.ajaxRequestSubType) {
//control processes so no actual ajax requests are required
case "multirequest_parent":
case "multilrequest_submit":
break;
default:
this.server_data[request_id].ajax = $.ajax({
headers: {
'X-CSRF-TOKEN': laravelCSRF//this is a constant from php JSCONSTANTS
},
url: this.url,
type: this.reqType,
data: requestbuild,
dataType: this.dataType,
success: function (server_response) {
var requestobj = SERVER_INTERFACES[server_response.interface_name]; //.server_data[request_id];
if (requestobj.server_data[request_id] != undefined) {//check existence - a reset might have been requested since query sent
requestobj.setRequestResult(server_response.request_id, server_response.data);
//check through request types to eventual detect a simple callback from client object
switch (server_response.ajaxRequestSubType) {
case "select":
case "call":
if (server_response.flag_multiRequestChild) {
var parentinterface_name = requestobj.interface_name;
var parentinterface_id = server_response.multirequest_parent;
var multiobj =
SERVER_INTERFACES[parentinterface_name].
server_data[parentinterface_id];
multiobj.request_returned++;
if (multiobj.request_returned == multiobj.request_total) {
requestobj.multiRequestFinish(requestobj.server_data[request_id].multirequest_parent);
}
} else if (server_response.callback != "") {
eval(server_response.callback + "(" + server_response.request_id + ",'" + requestobj.interface_name + "')");
}
break;
case "submit":
if (!server_response.ismultipart) {
if (server_response.callback != "") {
eval(server_response.callback + "(" + server_response.request_id + ")");
}
} else {
var multiobj = SERVER_INTERFACES[server_response.interface_name].server_data[requestobj.server_data[request_id].multisubmit_parent];
multiobj.submit_returned++;
if (multiobj.submit_returned == multiobj.submit_total) {
requestobj.multiSubmitFinish(requestobj.server_data[request_id].multisubmit_parent);
}
}
break;
case "jscsv":
var downloadobj = SERVER_INTERFACES[server_response.interface_name].server_data[request_id];
requestobj.downloadrun(downloadobj);
break;
default://need failover as cannot determine what to do
break;
}
} else {
var faildata = "error";
}
},
error: function (server_response) {
//parse unhelpful error 'data' to relocate correct ajax request object
var errordata = this.data.split("&");
var intefacename;
var requestid;
var errorobj = {isajaxerror: true};
for (var i in errordata) {
var keyval = errordata[i].split("=");
errorobj[keyval[0]] = keyval[1];
if (errordata[i].indexOf("request_id=") != -1) {
requestid = errordata[i].substr(errordata[i].indexOf("=") + 1);
}
if (errordata[i].indexOf("interface_name=") != -1) {
interfacename = errordata[i].substr(errordata[i].indexOf("=") + 1);
}
}
var parentobj = SERVER_INTERFACES[interfacename];
var requestobj = parentobj.server_data[requestid];
//new object required as out of scope
errorobj["responseText"] = server_response.responseText;
parentobj.setRequestResult(errorobj["request_id"], errorobj);
eval(errorobj["callback"] + "(" + errorobj["request_id"] + ")");
}
});
break;
}
return request_id;
}
/*
* handles ajax where data is not expected back such as an insert statement or email send
* but can expect a response message such as 'ok' or an error message
*/
Ajax_m.prototype.submit = function (type, submitdata, callback) {
this.request({ajaxRequestSubType: "submit", type: type, submitdata: submitdata, ismultipart: false, callback: callback});
}
/*
* 'multiSubmit' handles ajax where data is not expected back such as an insert statement or email send
* but can expect a response message such as 'ok' or an error message
* EXAMPLE
var multisub = [
{
type: "update",
data: {
table: "[xondbs1].stats.dbo.a_ppuser",
values: {'email': 'tim'},
matchfield: 'keyval', matchvalue: 'Q00010017'
}
},
{
type: "update",
data: {
table: "[xondbs1].stats.dbo.a_ppuser",
values: {'email': 'tim'},
matchfield: 'keyval', matchvalue: 'Q00010017'
}
}
];
ajaxdbobj.multiSubmit(multisub, "callbackfunctionname");
*/
Ajax_m.prototype.multiSubmit = function (submitobject, callback) {
var parent_request_id = this.request({ajaxRequestSubType: "multisubmit_parent", submit_total: count(submitobject), submit_returned: 0, id_list: [], submit: {}, response: {}, callback: callback});
for (var s in submitobject) {
var child_request_id = this.request({
ajaxRequestSubType: "submit",
multisubmit_parent: parent_request_id,
ismultipart: true,
type: submitobject[s].type,
submitdata: submitobject[s].data
});
this.server_data[parent_request_id].id_list[child_request_id] = s;
}
return parent_request_id;
}
/*
* sets up mutli queries to only run callback when all complete
* the requestobject is key=>query assoc to which results are assign the same key
* when all results complete the callback is run giving the request_id in the normal way
* to return the multi result object
*/
Ajax_m.prototype.multiRequest = function (requestobject, callback) {
var parent_request_id = this.request({ajaxRequestSubType: "multirequest_parent", request_total: count(requestobject), request_returned: 0, id_list: [], request: {}, data: {}, callback: callback});
for (var r in requestobject) {
/*var child_request = {
request: requestobject[r],
ajaxRequestSubType: "multirequest_child",
}*/
var child_request = requestobject[r];
child_request.multirequest_parent = parent_request_id;
child_request.flag_multiRequestChild = true;
var child_request_id = this.request(child_request);
this.server_data[parent_request_id].id_list[child_request_id] = r;
}
return parent_request_id;
}
/*
* sets up facility for javascript to download data locally
* there is no callback facility required as this is a one-way request
* with a url returned pointing to the resultant file, this is ultimately sent as a new
* window request to the file which will be handled on the native machine settings
*
* for integrity and security the server sets a unique filename ending
*
* First a meta query is sent to process what action to take - eg inform that data is emailed when ready if a length query
* This is then fed back to the user as to what is happening before the actual query can begin.
* #param type determines what download process should be used
* #param dataArgs determines how the data is retrieved
*/
Ajax_m.prototype.requestDownload = function (fileprefix, type, downloadData) {
view.dialogOpen({
title: "Download",
dialogbody: "preparing download . . .",
closeButton: false//change to false after test
});
this.request({ajaxRequestType: "requestDownload", fileprefix: fileprefix, ajaxRequestSubType: type, downloadData: downloadData});
//this.server_data[downloadid].callbacktype = action;
}
/*
* opens url to processed data downloadRequest in a new window / tab
*/
Ajax_m.prototype.downloadrun = function (reqobj) {
//getRequestResult
var meta = this.getRequestResult(reqobj.request_id);
switch (reqobj.ajaxRequestSubType) {
case "jscsv":
view.dialogOpen({
title: "Download",
dialogbody: "Your file download has finished processing.<br />Please ensure you have popups enabled for this site to be able to access the file.",
closeOK: true
});
window.open(meta.downloadurl, "download");
break;
case "dbcsv":
view.dialogOpen({
title: "Download",
dialogbody: meta.msg,
closeOK: true
});
this.request({ajaxRequestSubType: "downloadrun", filename: reqobj.filename, type: reqobj.type, downloadsource: reqobj.downloadsource}, '');
break;
}
}
/*
* kills data (returning requested will be ignored)
*/
Ajax_m.prototype.reset = function () {
for (var s in this.server_data) {
if (this.server_data[s].ajax) {
this.server_data[s].ajax.abort();
}
}
this.server_data = new Array();
this.request_index = 0;
}
/*
* relates misc data to query eg
*/
Ajax_m.prototype.setMisc = function (request_id, miscobject) {
this.server_data[request_id].misc = miscobject;
}
/*
* gets misc data to query eg
*/
Ajax_m.prototype.getMisc = function (request_id) {
return this.server_data[request_id].misc;
}
/*
* get orig query sent
*/
Ajax_m.prototype.setAjaxRequestType = function (type) {
this.reqType = type;
}
/*
* get orig query sent
*/
Ajax_m.prototype.setDataType = function (type) {
this.dataType = type;
}
/*
* get orig query sent
*/
Ajax_m.prototype.getRequest = function (request_id) {
return this.server_data[request_id].request;
}
/*
* return result data for given request id
*/
Ajax_m.prototype.getRequestResult = function (id) {
var data;//leave as undefined so code fails in the client
if (this.server_data[id]) {
data = this.server_data[id].data;
}
return data;
//return data;
}
/*
* return result data for given request id indexed by a field name
* if its not unique there will be data loss and a 'distinct' set will be returned
*/
Ajax_m.prototype.getRequestResultByCol = function (id, colname) {
var reqdata = this.getRequestResult(id);
var data = {};
for (var r in reqdata) {
data.r[colname] = data.r;
delete data.r[colname][colname];
}
return data;
//return data;
}
/**
* return a single value for given request id, if request id did actual generate
* multiple values then only the first is returned
* if this was a multirequest, the named key of the multi request is required
*/
Ajax_m.prototype.getRequestValue = function (id, multi_id) {
var retval;
if (!this.server_data[id].ismultiparent) {
retval = this.server_data[id].data[0];
} else {
retval = this.server_data[id].data[multi_id][0];
}
if (retval == undefined) {
retval = null;
}
return retval;
}
/*
* removes a query and data from memory
*/
Ajax_m.prototype.deleteRequest = function (request_id) {
delete this.server_data[request_id];
}
Ajax_m.prototype.error = function (serverData, st, ert) {
//all errors should have been handled, but just in case
var errorReport = "error";
errorReport += st;
alert("error");
}
/**********************************************************************************************************
INTENDED AS PRIVATE FUNCTIONS
**********************************************************************************************************/
/*
* sets result data for this instance for given query id - eliminates the need for eval unknown ajax data
*/
Ajax_m.prototype.setRequestResult = function (request_id, data) {
this.server_data[request_id].data = data;
}
/*
* compiles the data from the multi query parts into the array entry referenced by the query_index returned
* from client code calling the multiquery function. This also allows the required callback with a reference id to this data
*/
Ajax_m.prototype.multiRequestFinish = function (multirequestid) {
var requestobj = this.server_data[multirequestid];
var multidata = {};
var compactdata;
for (var i in requestobj.id_list) {
requestobj.data[requestobj.id_list[i]] = this.getRequestResult(i);
this.deleteRequest(i);
}
eval(requestobj.callback + "(" + multirequestid + ")");
}
/*
* finalises multisubmit and runs callback
*/
Ajax_m.prototype.multiSubmitFinish = function (multirequestid) {
var requestobj = this.server_data[multirequestid];
var multidata = {};
var compactdata;
for (var i in requestobj.id_list) {
//requestobj.data[requestobj.id_list[i]] = this.getRequestResult(i);
this.deleteRequest(i);
}
eval(requestobj.callback + "(" + multirequestid + ")");
}
}
There were quite a few repetitions in your code. Contrary to #Datadimension I did not restructure your code completely but was trying to show you ways of parameterizing a few of your expressions and functions:
$(document).ready(function() {
var labcatsubcat1=
$("label[for='id_category1'],#id_category1,label[for='id_subcategory1'],#id_subcategory1 ")
.hide();
$('select[name=subcategory],select[name=subcategory1]')
.html('<option value="Not selected" selected disabled>Select Category...</option>');
// called when category field changes from initial value:
$('#id_group').change(function() {
labcatsubcat1.toggle($(this).val()=='premium');
})
$('#id_category,#id_category1').change(function() {
var $this = $(this), postfix=this.id.match(/1*$/)[0];
if ($this.find('option:selected').index() > 0) {
category_id = $('select[name=category'+postfix+']').val();
request_url = '/get_subcategory/' + category_id + '/';
$.ajax({
url: request_url,
type: "GET",
success: function(data) {
$('select[name=subcategory'+postfix+']').empty();
$.each(data, function(key, value) {
$('select[name=subcategory'+postfix+']').append('<option value="' + key + '">' + value + '</option>');
});
}
})
}
});
["keywords,Keywords,100","description,Description,250"].forEach(e=>{
var[id,nam,len]=e.split(",");
$("label[for='id_"+id+"']").html(nam+" 0/"+len);
$('#id_'+id).keyup(function() {
var charsno = $(this).val().length;
$("label[for='id_"+id+"']").html(nam+" (" + charsno + "/"+len+")");
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Unfortunately, this is not (yet) a working snippet, as you did not post your HTML ...
Just a short explanation regarding postfix: This variable will hold the string "1" or "" depending on, whether the this refers to the #id_category1 or the #id_category DOM-element.
One thing I'd do is combine the two AJAX requests. You can use multiple selectors for the change handler. Something like $('#id_category', '#id_category1').change(etc.... I'm sure you could find a way to target exactly which one is handling which request. You can use multiple selectors for the other functions as well as per the docs.
If the file is relatively short (~100 - 200 lines) I think you're fine keeping everything all in one place. Otherwise, definitely separate the functions into files and then require them as needed. You can use requireJS for this among others.

Get all selected ids of jqgrid in external javascript function

I am using multi-select grid functionality in my application and it is working as i expected. But the issue is i need to get all the selected records across the pagination in external javascript function. Below is my code,
function createCommodity(){
$.ajax({
url : 'commoditycategory.do?method=listCommodity' + '&random='
+ Math.random(),
type : "POST",
async : false,
success : function(data) {
$("#list2").jqGrid('GridUnload');
var newdata = jQuery.parseJSON(data);
var wWidth = $(window).width();
var dWidth = wWidth * 0.7;
var wHeight = $(window).height();
var dHeight = wHeight * 0.5, idsOfSelectedRows = [];
jQuery("#list2").jqGrid({
data : newdata,
datatype : "local",
colNames : [ "id", "Commodity Code",
"Commodity Description", "Commodity Category" ],
colModel : [
{
name : 'id',
index : 'id',
hidden : true,
editable : true
},
{
name : 'commodityCode',
index : 'commodityCode',
align : "center",
editable : true,
editrules : {
required : true
}
},
{
name : 'commodityDesc',
index : 'commodityDesc',
align : "center",
editable : true,
editrules : {
required : true
}
},
{
name : 'commodityCategoryId',
index : 'commodityCategoryId',
align : "center",
// hidden : true,
editable : true,
edittype : "select",
editoptions : {
dataUrl : 'commoditycategory.do?method=parentCategory'
+ '&random=' + Math.random()
},
editrules : {
edithidden : true,
required : true
// custom : true
}
} ],
pager : "#pager2",
rowNum : 10,
rowList : [ 10, 20, 50 ],
height : "230",
width : dWidth,
onSelectRow: function (id, isSelected) {
var p = this.p, item = p.data[p._index[id]], i = $.inArray(id, idsOfSelectedRows);
item.cb = isSelected;
if (!isSelected && i >= 0) {
idsOfSelectedRows.splice(i,1); // remove id from the list
} else if (i < 0) {
idsOfSelectedRows.push(id);
}
},
loadComplete: function () {
var p = this.p, data = p.data, item, $this = $(this), index = p._index, rowid, i, selCount;
for (i = 0, selCount = idsOfSelectedRows.length; i < selCount; i++) {
rowid = idsOfSelectedRows[i];
item = data[index[rowid]];
if ('cb' in item && item.cb) {
$this.jqGrid('setSelection', rowid, false);
}
}
},
multiselect : true,
cmTemplate : {
title : false
}
});
$grid = $("#list2"),
$("#cb_" + $grid[0].id).hide();
$("#jqgh_" + $grid[0].id + "_cb").addClass("ui-jqgrid-sortable");
cbColModel = $grid.jqGrid('getColProp', 'cb');
cbColModel.sortable = true;
cbColModel.sorttype = function (value, item) {
return typeof (item.cb) === "boolean" && item.cb ? 1 : 0;
};
}
});
}
Till now its working great. Its holding correct rows which are selected across pagination.
And My external JS function where i need to get the selected rowids include pagination is,
function updateCommodity() {
var grid = jQuery("#list2");
var ids = grid.jqGrid('getGridParam', 'selarrrow'); // This only returns selected records in current page.
if (ids.length > 0) {
var html = "<table id='commodityTable' class='main-table' width='100%' border='0' style='border:none;border-collapse:collapse;float: none;'><thead><td class='header'>Commodity Code</td><td class='header'>Commodity</td><td class='header'>Action</td></thead><tbody>";
for ( var i = 0, il = ids.length; i < il; i++) {
var commodityCode = grid.jqGrid('getCell', ids[i],
'commodityCode');
var commodityDesc = grid.jqGrid('getCell', ids[i],
'commodityDesc');
html = html
+ "<tr class='even' id='row" + i + "'><td><input type='text' name='commodityCode' id='geographicState"+i+"' class='main-text-box' readonly='readonly' value='" + commodityCode + "'></td>";
html = html
+ "<td><input type='text' name='commodityDesc' id='commodityDesc"+i+"' class='main-text-box' readonly='readonly' value='" + commodityDesc + "'></td>";
html = html
+ "<td><a style='cursor: pointer;' onclick='deleteRow(\"commodityTable\",\"row"
+ i + "\");' >Delete</a></td></tr>";
}
html = html + "</tbody></table>";
$("#commodityArea").html(html);
}
}
Update I have fiddled the issue for providing more clarity about the issue.
First of all I want remind that you use the code which I posted in the answer.
I see that the solution of your problem is very easy. The list of options of jqGrid can be easy extended. If you just include new property in the list of options
...
data : newdata,
datatype : "local",
idsOfSelectedRows: [],
...
you will don't need more define the variable idsOfSelectedRows (see the line var dHeight = wHeight * 0.5, idsOfSelectedRows = []; of you code). To access new option you can use
var ids = grid.jqGrid('getGridParam', 'idsOfSelectedRows');
instead of var ids = grid.jqGrid('getGridParam', 'selarrrow');. To make the code of onSelectRow and loadComplete callbacks working with idsOfSelectedRows as jqGrid option you should just modify the first line of the callbacks from
var p = this.p, ...
to
var p = this.p, idsOfSelectedRows = p.idsOfSelectedRows, ...
It's all.
UPDATED: See http://jsfiddle.net/OlegKi/s2JQB/4/ as the fixed demo.

jQuery Plugin settings on multiple instances

I have a problem with settings on multiple instances on a jquery plugin.
If I cast my plugin multiple times and alert them on an onclick binding, it always alerts the same parameter.
This is my plugin.
/**
* Provide user search for input elements.
*
* Call this jQuery plugin on an input element to add a button
* for searching the active directory on userdata.
* Returned data are saved in declared target input elements.
*
* Depends:
* jQuery UI Dialog
*
* #license http://www.opensource.org/licenses/mit-license.php
* #version 1.0
*/
;(function ( $, window, document, undefined ){
var PROP_NAME = 'userdata';
var IS_IFRAME = ( self !== top ) ? true : false;
var rfuuid = new Date().getTime();
var $jParent = ( self !== top ) ? window.parent.jQuery.noConflict() : $;
/**
* Userdata manager.
* Use the singleton instance of this class, $.userdata, to interact with the date picker.
* Settings for (groups of) date pickers are maintained in an instance object,
* allowing multiple different settings on the same page.
*/
function Userdata() {
this.regional = [];
this.regional[''] = {
abortText: 'Abbrechen',
acceptText: 'Hinzufügen',
errorTitle: 'Fehler beim Suchen',
errorFilterText: 'Suchkriterien einschränken.',
errorVoidText: 'Der gesuchte Kontakt konnte nicht gefunden werden.',
errorScriptText: 'Bei der Suche ist ein Fehler aufgetreten. Falls der Fehler wieder auftritt, wenden Sie sich bitte an Ihren Webadministrator.',
searchText: 'Durchsuchen',
selectionTitle: 'Namen überprüfen',
selectionInfoText: '"%s" kommt mehrmals vor.',
selectionDescText: 'Wählen Sie die Adresse aus, die Sie verwenden möchten:'
};
this._defaults = {
ajaxURL: 'userdata.php',
buttonClass: 'rf-button secondary',
buttonContainer: '<div>',
buttonContainerClass: 'grid_2',
targets: {}
}
$.extend(this._defaults, this.regional['']);
}
$.extend(Userdata.prototype, {
/**
* Override the default settings for all instances of the userdata plugin.
*
* #param object settings The new settings to use as defaults (anonymous object).
* #return the manager object.
*/
setDefaults: function( settings ){
$.extend(this._defaults, settings);
return this;
},
/**
*
*
* #param object input DOM input element.
* #param object settings Settings for attaching new userdata functionality.
*/
_attachDialog: function( input, settings ){
var settings = $.extend(this._defaults, settings);
if ( !document.getElementById('rf-userdata-dialog') ){
var inst = $jParent('<div id="rf-userdata-dialog"></div>').appendTo('body');
inst.dialog({ autoOpen: false, close: function(){ $jParent('body').css('overflow', 'auto'); input.focus(); }, modal: true, resizable: false }).after('<span class="ui-dialog-footer" /><span class="ui-dialog-footer-edge" />');
}
else {
var inst = $('#rf-userdata-dialog');
}
input.settings = settings;
$(input).data('settings', settings);
this._attachButton(input, inst);
},
/**
*
*
* #param object input DOM input element.
* #param object inst jQuery dialog instance.
*/
_attachButton: function( input, inst ){
var manager = this,
$input = $(input);
// Create search button.
var $button = $('<button>').attr('type', 'button').html(input.settings.searchText).addClass(input.settings.buttonClass);
alert(dump($(input).data('settings'))); // WORKS FINE, everything is unique.
/**
* Bind manager._searchUserdata() function on button click.
*/
$button.bind('click', { settings : $(input).data('settings') }, function(e){
alert(dump(e.data.settings)); // DOES NOT WORK, always settings from last plugin call...
//manager._searchUserdata(input, inst);
});
/**
* Insert container with search button after input field.
*/
$input.closest('[class*="grid_"]').after(function(){
return $(input.settings.buttonContainer).addClass(input.settings.buttonContainerClass).append($button);
});
/**
* Change default enterkey behaviour on triggering the userdata button.
*/
$input.bind('focusin', function(){
$input.bind('keydown.enterOpen', function(e){
if ( e.keyCode === 13 ){
$button.trigger('click');
return false;
}
});
});
/**
* Unbind keydown event with enterOpen namespace.
*/
$input.bind('focusout', function(){
$input.unbind('keydown.enterOpen');
});
},
/**
*
*
* #param object input DOM input element.
* #param object inst jQuery dialog instance.
*/
_searchUserdata: function( input, inst ){
var manager = this,
$input = $(input),
value = $input.val();
/**
* Perform an Ajax request to get the userdata of specified user.
*/
$.ajax({
url: input.settings.ajaxURL,
dataType: 'json',
data: 'value=' + encodeURIComponent(value),
/**
* A pre-request callback function.
* Returning false in the beforeSend function will cancel the request.
*/
beforeSend: function(){
// If value is smaller than two characters is equal space character
// call showError and cancel ajax call.
if ( value.length <= 2 || value === ' ' || value === '' ){
manager._showError(input.settings.errorFilterText, inst, input);
return false;
}
},
/**
* A function to be called if the request succeeds.
*
* #see manager._showError() for error display.
* #see manager._checkName() for selecting dialog.
*
* #param object data LDAP userdata returned from server.
*/
success: function( data ){
if ( $.isEmptyObject(data) ){
manager._showError(input.settings.errorVoidText, inst, input);
}
else if ( data.error === 4 ){
manager._showError(input.settings.errorFilterText, inst, input);
}
else {
// If request returned more than one user, call checkName() function.
if ( data.length > 1 ){
manager._checkName(input, inst, data);
}
else {
manager._setUserdata(inst, data[0], input);
}
}
},
/**
* A function to be called if the request fails.
*
* #see manager._showError() for more information.
*
* #param object jqXHR XMLHttpRequest object.
* #param string textStatus Description of occurred error.
* #param object errorThrown Exception object.
*/
error: function( jqXHR, textStatus, errorThrown ){
manager._showError(input.settings.errorScriptText, inst, input);
}
});
},
/**
*
*
* #param string error Error to display.
* #param object inst jQuery dialog instance.
* #param object input DOM input element.
*/
_showError: function( error, inst, input ){
inst.html('<div class="ui-dialog-container">' + error + '</div>')
inst.dialog({ title: input.settings.errorTitle, width: 400 });
inst.dialog('open');
},
/**
*
*
* #param object input DOM input element.
* #param object inst jQuery dialog instance.
* #param array data LDAP userdata.
*/
_checkName: function( input, inst, data ){
var manager = this,
$container = $('<div>').addClass('ui-dialog-container').html('<p>' + sprintf(input.settings.selectionInfoText, $(input).val()) + '</p><p>' + input.settings.selectionDescText + '</p>'),
$tableWrapperOuter = $('<div>').addClass('rf-select-list-wrapper-outer'),
$tableWrapperInner = $('<div>').addClass('rf-select-list-wrapper-inner').css('height', 240),
$table = $('<table>').addClass('rf-select-list'),
$thead = $('<thead>').html('<tr><th>Name</th><th>Position</th><th>Telefon</th><th>Ort</th><th>E-Mail</th><th>Alias</th></tr>'),
$tbody = $('<tbody>');
// Loop trough userdata and create a table row for each entry.
for ( var i = 0, length = data.length; i < length; i++ ){
var $row = $('<tr>').html(function(){
this.onselectstart = function(){ return false; }
//return '<td class="user-icon">' + data[i].sn + ' ' + data[i].givenname + '</td><td>' + data[i].title + '</td><td>' + data[i].telephonenumber + '</td><td>' + data[i].location + '</td><td>' + data[i].mail + '</td><td>' + data[i].cn + '</td>';
return '<td class="user-icon">' + data[i].sn + ' ' + data[i].givenname + '</td><td>' + data[i].title + '</td><td>' + data[i].location + '</td><td>' + data[i].cn + '</td>';
});
$row.bind('click', { obj: data[i] }, function(e){
var $this = $(this);
// Temp-save data from selection for ok-button.
inst.selection = e.data.obj;
$this.siblings().removeClass('ui-state-active');
$this.addClass('ui-state-active');
});
$row.bind('dblclick', { obj: data[i] }, function(e){
inst.dialog('close');
manager._setUserdata(inst, e.data.obj, input);
});
$row.appendTo($tbody);
}
// Trigger first row selection.
$tbody.find('tr').first().trigger('click');
// Hide scrollbar on form body to prevent scrolling problem.
$jParent('body').css('overflow', 'hidden');
// Create buttons and append them to a container.
var $buttonAccept = $('<button>').addClass("rf-button primary").html(input.settings.acceptText).bind('click', function(){
inst.dialog('close');
manager._setUserdata(inst, inst.selection, input);
});
var $buttonAbort = $('<button>').addClass("rf-button secondary").html(input.settings.abortText).bind('click', function(){
inst.dialog('close');
});
// Toggle 'rf-button-hover' class on buttons hover state.
$buttonAccept.hover(function(){ $buttonAccept.toggleClass('rf-button-hover'); });
$buttonAbort.hover(function(){ $buttonAbort.toggleClass('rf-button-hover'); });
var $buttonContainer = $('<div>').addClass('float-right').append($buttonAccept, $buttonAbort);
// Append dialog html to container.
$container.append($tableWrapperOuter.append($tableWrapperInner.append($table.append(/*$thead,*/ $tbody))), $buttonContainer);
inst.html($container);
inst.dialog({ title: input.settings.selectionTitle, width: 800 });
inst.dialog('open');
},
/**
*
*
* #param object inst jQuery dialog instance.
* #param array data LDAP userdata.
*/
_setUserdata: function( inst, data, input ){
for ( var target in input.settings.targets ){
var values = [];
if ( typeof(input.settings.targets[target]) === 'object' ){
for ( var i = 0, length = input.settings.targets[target].length; i < length; i++ ){
values.push(data[input.settings.targets[target][i]]);
}
}
else {
values.push(data[input.settings.targets[target]]);
}
$(target).val(values.join(' '));
}
}
});
/**
* Invoke the userdata functionality.
*
* #param object options Settings for attaching new userdata functionality.
* #return jQuery object.
*/
$.fn.userdata = function( options ){
// Verify an empty collection wasn't passed.
if ( !this.length ){
return this;
}
/**
* Loop through each plugin object.
*/
return this.each(function(){
$.userdata._attachDialog(this, options);
});
};
$.userdata = new Userdata();
$.userdata.uuid = new Date().getTime();
})( jQuery, window, document );
I call it in my html multiple times:
$('#inputid_1').userdata({ targets: {'#targetid_1': 'cn'} });
$('#inputid_2').userdata({ targets: {'#targetid_2': 'phone'} });
Now if you look at the _attachButton method, there are two alerts. One outside the click bind and one inside the click bind. Outside the click bind, the settings are unique foreach plugin call. Inside the click bind, it always alerts the settings from the last call, even if I pass them with event.data.
Extend the settings like this:
var settings = $.extend(settings, this._defaults); // invert the params
or
var settings = $.extend({}, this._defaults, settings);
Why ?
The $.extend() takes as first param a target. So you were merging the properties of this._default with the settings and not the contrary.
The second form (with {}) says: ignore target, let both this._default and settings untouched, simply return a merged object (hope i'm clear ^^).
See jQuery documentation about .extend().

Categories