JQGrid MultiSelect getting the column data - javascript

Is there a way for the JQGrid to return an array of column Data for using multiSelect as opposed to just an array of rowIds ?
At the moment I can only return the last column data that was selected.
jQuery("#buttonSelected").click(function() {
var ids = jQuery("#relatedSearchGrid").getGridParam('selarrrow');
var count = ids.length;
for (var i = 0; i < count; i++) {
var columnData = $("#relatedSearchGrid").find("tbody")[0].rows[$("#relatedSearchGrid").getGridParam('selrow') - 1].cells[1].innerHTML;
alert("In the loop and " + columnData );
}
if (count == 0) return;
var posturl = '<%= ResolveUrl("~") %>Rel******/AddSelected****/' + ids;
if (confirm("Add these " + count + " Docs?")) {
$.post(posturl,
{ ids: columnData },
function() { jQuery("#relatedSearchGrid").trigger("reloadGrid") },
"json");
}
})

Use getRowData to get the data for each row:
var rowData = $("#relatedSearchGrid").getRowData(ids[i]);
var colData = rowData.Name_Of_Your_Column;

var userListjqGrid = $('#UserListGrid'),
selRowId = userListjqGrid.jqGrid('getGridParam', 'selrow'),
userId = userListjqGrid.jqGrid('getCell', selRowId, 'UserId'),
userName = userListjqGrid.jqGrid('getCell', selRowId, 'UserName'),
subIds = $(subgridTableId).getGridParam('selarrrow'),
accessRuleIds = [];
for (var i = 0; i < subIds.length; i++) {
accessRuleIds[i] = $(subgridTableId).getRowData(subIds[i]).AccessRuleId;
}

Related

Jquery ajax send json

Javascript:
function add_content(count)
{
var result = {};
var row = new Array();
for (i = 0; i < count; i++)
{
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}
$.ajax({
url: "ajax-functions.php",
data: {json_data: JSON.stringify(row)},
type: 'post',
success: function (output) {
alert(output);
}
})
}
Php:
$img_desc = json_decode($_POST['json_data'],TRUE);
$count = count($img_desc);
echo 'count:'.$count;
print_r($img_desc);
I want to send json to from JS to PHP. This above code works well, but it send the last data of the for loop is set in all the objects.
How to fix it? Is this right way?
Thanks.
Push a new object on each round of the loop into to the array
for (var i = 0; i < count; i++) {
row.push({
"img_src": $("#img_" + i).attr('src'),
"desc": $("#desc_" + i).val()
});
}
fiddle
Move result declaration inside for:
var row = new Array();
for (i = 0; i < count; i++)
{
var result = {};
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}
or it can be done more elegantly:
var row = new Array();
var result;
for (i = 0; i < 10; i++)
{
result = row[ row.push({}) - 1 ];
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
}
You can make the keys of result array also dynamic
Since you are not making it dynmamic, its getting over ridden in the next loop
EDIT:
for (i = 0; i < count; i++)
{
var result = {};
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}

Angular ngGrid data presentation

I'm new to Angular and my experience with Javascript is not very extensive. I am failing to show data in ngGrid using following code. What is the problem?
In essence. I am loading data from a web-service, performing a transform (pivot) on it and then I want to present it in a grid.
Please see the following
app.js -> starting poing
var konstruktApp= angular.module('konstruktApp',['ngGrid']);
dataService.js -> web service call
'use strict';
konstruktApp.service('DataService',function DataService($http){
var callHttp = function(){
delete $http.defaults.headers.common['X-Requested-With'];
return $http.get("http://83.250.197.214/konstrukt.service/Konstrukt.SL.DummyBudgetService.svc/GetDummyBudgetData/");
};
return {
getDummyData: callHttp
};
});
ngGridController.js -> where the logic resides...
$scope.getData = DataService.getDummyData;
$scope.gridOptions = {data:'result'};
var getData = function() {
$scope.getData().then(function (response) {
var res = pivotData(response.data);
$scope.result = res.data.PivotedRows;
$scope.columns = res.cols;
console.log('from the success handler at ' + new Date());
}, function (reason) {
console.log('failed: ');
console.log(reason);
});
};
..and here is the logic that "pivots" the data
var pivotData = function(data) {
var firstColumn = "Dim1";
var secondColumn = "Period";
var columns = [];
columns.push({
field: firstColumn,
enableCellEdit: false
});
var pivotedArray = {};
pivotedArray.PivotedRows = [];
var rowItems = [];
var rowArray = {};
var previusFirstColumnValue = -1;
var firstColumnValue = 1;
//for each row
for (var i = 0; i < data.Rows.length; i = i + 1) {
//firstColumnValue = $scope.dataCollection.Rows[i].FindCell.Cells[firstColumn].Value;
firstColumnValue = findCell(data.Rows[i].Cells, firstColumn).Value;
//var secondColumnValue = data.Rows[i].Cells[secondColumn].Value;
var secondColumnValue = findCell(data.Rows[i].Cells, secondColumn).Value;
//if first column value has changed, add new row
if (firstColumnValue != previusFirstColumnValue) {
if (i !== 0) {
for (var j = 0; j < rowItems.length; j = j + 1) {
rowArray[rowItems[j].name] = rowItems[j].value;
}
pivotedArray.PivotedRows.push( rowArray);
rowArray = {};
rowItems = [];
}
rowItems.push({
name: firstColumn,
//value: $scope.dataCollection.Rows[i].Cells[firstColumn].Value
value: findCell(data.Rows[i].Cells, firstColumn).Value
});
}
//if (columns.indexOf({field: secondColumnValue}) == -1) {
if (i < 12) {
columns.push({
field: secondColumnValue,
editableCellTemplate: "<input ng-class=\"'colt' + col.index\" ng-input=\"COL_FIELD\" ng-blur=\"lostFocus()\" ng-model=\"COL_FIELD\" ng-change=\"dataChanged(col,row,row.entity)\"/>",
enableCellEdit: true
});
}
rowItems.push({
name: secondColumnValue,
value: findCell(data.Rows[i].Cells, secondColumn).Value
});
previusFirstColumnValue = firstColumnValue;
}
for (var k = 0; k < rowItems.length; k = k + 1) {
rowArray[rowItems[k].name] = rowItems[k].value;
}
// $scope.columns = columns;
pivotedArray.PivotedRows.push( rowArray);
return {data: pivotedArray, cols: columns};
};
plnkr: http://plnkr.co/edit/ZqC7696xGbUtuWGIvnYs?p=preview
EDIT: The data correlation rows<-> columns is correct, I suspect there is something wrong with data in the pivotedArray.PivotedRows array.
It turned out that moving the code to a new plnkr made the difference. Now, thats a few hours of my life that I want back :)

generate list of variables from a FOR loop

var select = [];
for (var i = 0; i < nameslots; i += 1) {
select[i] = this.value;
}
This is an extract of my code. I want to generate a list of variables (select1, select2, etc. depending on the length of nameslots in the for.
This doesn't seem to be working. How can I achieve this? If you require the full code I can post it.
EDIT: full code for this specific function.
//name and time slots
function gennametime() {
document.getElementById('slots').innerHTML = '';
var namelist = editnamebox.children, slotnameHtml = '', optionlist;
nameslots = document.getElementById('setpresentslots').value;
for (var f = 0; f < namelist.length; f += 1) {
slotnameHtml += '<option>'
+ namelist[f].children[0].value
+ '</option>';
};
var select = [];
for (var i = 0; i < nameslots; i += 1) {
var slotname = document.createElement('select'),
slottime = document.createElement('select'),
slotlist = document.createElement('li');
slotname.id = 'personname' + i;
slottime.id = 'persontime' + i;
slottime.className = 'persontime';
slotname.innerHTML = slotnameHtml;
slottime.innerHTML = '<optgroup><option value="1">00:01</option><option value="2">00:02</option><option value="3">00:03</option><option value="4">00:04</option><option value="5">00:05</option><option value="6">00:06</option><option value="7">00:07</option><option value="8">00:08</option><option value="9">00:09</option><option value="10">00:10</option><option value="15">00:15</option><option value="20">00:20</option><option value="25">00:25</option><option value="30">00:30</option><option value="35">00:35</option><option value="40">00:40</option><option value="45">00:45</option><option value="50">00:50</option><option value="55">00:55</option><option value="60">1:00</option><option value="75">1:15</option><option value="90">1:30</option><option value="105">1:45</option><option value="120">2:00</option></optgroup>';
slotlist.appendChild(slotname);
slotlist.appendChild(slottime);
document.getElementById('slots').appendChild(slotlist);
(function (slottime) {
slottime.addEventListener("change", function () {
select[i] = this.value;
});
})(slottime);
}
}
You'll have to close in the iterator as well in that IIFE
(function (slottime, j) {
slottime.addEventListener("change", function () {
select[j] = this.value;
});
})(slottime, i);
and it's only updated when the element actually change
The cool thing about JavaScript arrays is that you can add things to them after the fact.
var select = [];
for(var i = 0; i < nameSlots; i++) {
var newValue = this.value;
// Push appends the new value to the end of the array.
select.push(newValue);
}

How to add dynamically HTML element using JavaScript and Firefox Add-on SDK

I am developing a simple add-on with Firefox SDK that allows the user to review the stored data.
I would like to show the items in a panel with a table. The table is created dynamically with the data incoming from the data-base. Firstly, In the JavaScript code I create the items with their properties, then I create a table with the properties as row and I append the items with the value of each properties.
I have some problems: the table has only the item's name as first row and the properties name as first column without the value in the cells. It seems that the code is not executed in order, but it seems that the faster functions are executed first.
This is the code:
self.on('message', function() {
var container = $('#container');
container.empty();
items = [];
self.port.emit('getItem');
});
self.port.on('items', function(response) {
var ok = 0;
var items = [];
var table = $('#tableContainer #table').clone();
var container = $('#container');
table.append("<tr id=first><th> </th></tr>");
var json = eval('('+ response + ')');
for (var i = 0, len = json.length; i < len; ++i) {
var item = {
id: json[i],
properties: []
};
items.push(item);
}
items.forEach ( function(item) {
table.find('#first').append("<th id="+item.id+">"+item.id+"</th>");
self.port.emit('detailsItem', item.id);
self.port.on('details'+item.id, function(response) {
var details = eval('('+ response + ')');
var description = [];
ndet = details.length;
var len = details.length;
for (var i = 0; i < len;) {
var detail = {
dimension : details[i].dimension,
value : details[i].value
}
description.push(detail);
++i;
}
item.properties = description;
});
});
self.port.emit('getDimension');
self.port.on('dimension', function(response) {
var dimensions = eval('('+ response + ')');
for(var cont = 0, l = dimensions.length; cont < l; ++cont) {
table.append("<tr id=dimension"+cont+"><td>"+dimensions[cont]+"</td></tr>");
items.forEach( function(item) {
var prop = [];
prop = item.properties;
var lun = prop.length;
for( var p =0;p < lun;) {
if(item.properties[p].dimension == dimensions[cont]) { table.find('#dimension'+cont).append("<td>"+item.properties[p].value+"</td>");
}
else {
table.find('#dimension'+cont).append("<td> --- </td>");
}
++p; }
});
};
});
container.append(table);
});

JavaScript - Generate Kendo Ui Grid using xml Data

I've Been using XSLT to display my xml page. I make use of the following to get the data from the xml file:
< xsl:value-of
select="ClinicalDocument/component/structuredBody/component[3]/section/text/table/tbody"/
>
After this, I have the following javascript to clean up the data and do the conversion:
-----------Get Content for Grids----------
//Split Content into array
var purposeArray = document.getElementById('purposeOfVisit').innerHTML.split("\n");
var activeProblemArray = document.getElementById('activeProblems').innerHTML.split("\n");
//------------ Remove All Unwanted Values-----------\\*/
var newDataString ="";
for( var k = 0; k < purposeArray.length; k++ )
{
newDataString += purposeArray[k] + "__";
}
newDataString = newDataString.replace(/ /g,"");
newDataString = newDataString.replace(/__________/g,"__-__");
var newDataArray = newDataString.split("__");
//------------- Save Values in final Array -------------\\*/
var semiFinalArray = new Array();
for( var x=0; x < newDataArray.length; x++)
{
if(newDataArray[x].length != 0)
{
semiFinalArray.push(newDataArray[x]);
}
}
var finalArray = new Array();
var counter = 0;
//------------ Find Number of Columns in row ------------\\*/
var numberOfRows = document.getElementById('numberOfRows').innerHTML;
var numberOfColumns = document.getElementById('numberOfColumns').innerHTML;
var columnsPerRow = parseInt(numberOfColumns) / parseInt(numberOfRows);
//------------------------------Testing ------------------------------//
var dataNamePre = "dataValue";
var temporaryArray = new Array();
var dataName;
//----------- Generate Grid Values -----------//
for( var b=0 ; b < semiFinalArray.length ; b = b + columnsPerRow)
{
var problemComment = "";
counter = 0;
var obj;
for( var a=0 ; a < columnsPerRow ; a++)
{
dataName = dataNamePre + counter.toString() + "";
//-------Generate Grid Titles------//
temporaryArray.push("Title " + (counter+1));
var key = "key"+a;
obj = { values : semiFinalArray[b+a] };
var problemComment = "";
finalArray.push(obj);
counter++;
}
}
//---------------------Generate GridArray---------------------------//
var gridArray = [];
var gridArrayHead = new Array();
counter = 0;
var objectValue = new Array();
for( var x = 0; x < finalArray.length; x++ )
{
objectValue = { head:temporaryArray[x], values: finalArray[x].values }
gridArray.push(objectValue);
}
var provFacilities = [];
for( var x = 0; x < finalArray.length; x++ )
{
provFacilities[x] =
{
head:temporaryArray[x], values: finalArray[x].values
}
}
//alert(gridArray);
$("#grid").kendoGrid(
{
columns:
[{
title:gridArray.head,
template:'#= values #'
}],
dataSource: {
data:finalArray,
pageSize:10
},
scrollable:false,
pageable:true
});
This may be a roundabout method, but I'm still prettry new to this method of coding.
Currently, all the data is being presented in one column, with the last value in my temporaryArray as the title for the column.
Everything works until I try to set the DataSource for the Kendo Grid. When working in the columns property in the grid, I made the following change:
title:gridArray[0].head
When this is done, the title is changed to the first value in the array.
What I want to know is how can I generate columns in the Kendo Grid According to the title? Is there a way to loop through all the values and create the objects from there, seeing that the date that is being sent to the grid are objects in an Array?
What I basically want is something to make this work, without the repitition:
var myGrid = $("#grid").kendoGrid( { columns: [ {
title: temporaryArray[0],
field: finalArray[0].values }, {
title: temporaryArray[1],
field: finalArray[1].values }, {
title: temporaryArray[2],
field: finalArray[2].values }, {
title: temporaryArray[3],
field: finalArray[3].values }, {
title: temporaryArray[4],
field: finalArray[4].values } ]
)};
Any help appreciated, thanks!
This issue has been fixed using the following coding:
var arrayData = [];
for( var x = 0; x < semiFinalArray.length; x=x+5 )
{
var tempArr = new Array();
for( var y = 0; y < 5; y++ )
{
var num = x + y;
tempArr.push(semiFinalArray[num]);
}
arrayData.push(tempArr);
}
var dataTitles = [];
for( var x = 0; x < titleArray.length; x++ )
{
var head = "";
head = titleArray[x];
head = head.replace(/ /g,"");
dataTitles.push(head);
}
var counter = 0;
var columnDefs = [];
for (var i = 0; i < columnsPerRow.length; i++)
{
if (counter == (columnsPerRow - 1))
{
counter = 0;
}
columnDefs.push({ field: dataTitles[counter], template: arrayData[i].values });
counter++;
}
// Create final version of grid array
var gridArray = [];
for (var i = 0; i < arrayData.length; i++)
{
var data = {};
for (var j = 0; j < dataTitles.length; j++)
{
data[dataTitles[j]] = arrayData[i][j];
}
gridArray.push(data);
}
// Now, create the grid using columnDefs as argument
$("#grid").kendoGrid(
{
dataSource:
{
data: gridArray,
pageSize: 10
},
columns: columnDefs,
scrollable: false,
pageable: true
}).data("kendoGrid");
With this, the data is displayed in the DataGrid.

Categories