Please - need syntax for setting variables from jqGrid getRowData
property
Looping thru rows - just need to pull the ID and Phrase column values into variables
gridComplete: function () {
var allRowsInGrid = $('#list').jqGrid('getRowData');
for (i = 0; i < allRowsInGrid.length; i++) {
pid = allRowsInGrid[i].ID;
vPhrase = allRowsInGrid[i].Phrase;
vHref = "<a href='#' onclick='openForm(" + pid + ", " + vPhrase + ")'>View</a>";
}
},
Was able to get ID easy enough with getDataIDs :-)
Need help with getting specific column values for pid and vPhrase for i
Cheers
Try this:
var ids = jQuery("#list").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++)
{
var rowId = ids[i];
var rowData = jQuery('#list').jqGrid ('getRowData', rowId);
console.log(rowData.Phrase);
console.log(rowId);
}
Please Note: If your goal is to add a link to cell which calls a javascript method you can achieve this by using formatter like given below, formatter should be added to colModel like you add other column properties like name,index,width,align etc, so you can avoid the iteration over row data
formatter: function(cellvalue, options, rowObject) {
return "<a href='#' onclick='openForm("
+ rowObject.ID + ", "
+ rowObject.Phrase
+ ")'>View</a>";
}
This is what I use when I want to get Data by RowID for specific Cell.
var selRow = jQuery("#list10").jqGrid('getGridParam','selarrrow'); //get selected rows
for(var i=0;i<selRow.length;i++) //iterate through array of selected rows
{
var ret = jQuery("#list10").jqGrid('getRowData',selRow[i]); //get the selected row
name = ret.NAME; //get the data from selected row by column name
add = ret.ADDRESS;
cno = ret.CONTACTNUMBER
alert(selRow[i] +' : ' + name +' : ' + add +' : ' + cno);
}
Related
I have multiple tables. when looping through each table.innerHtml print all tables one by one.but when convert into object it only gives one table object.
$( ".table" ).each(function( index ,e) {
let tableId = $(this).closest('table').attr('id')
var table = document.getElementById(tableId);
console.table(table.innerHTML+"tb");
let myObj = {
table: [],
add_rows: []
};
for (var i = 0; row = table.rows[i]; i++) {
let tr_obj = [];
for (var j = 0; col = row.cells[j]; j++) {
var drop_down = $("#drop\\[" + j + "\\]").val()
var text_value = $("#text\\[" + i + "\\]\\[" + j + "\\]").val();
tr_obj.push(create_object(drop_down, text_value));
}
myObj['table'].push(tr_obj);
}
console.log(JSON.stringify(myObj['table'])+"ttt")
var div="div"+tableId
var hidden="entry_field_"+tableId+""
document.getElementById(hidden).value = JSON.stringify(myObj).replace(/\\/g, "")
});
when we console table.InnerHtml it gives print both table.but MyObj gives same table object.
I've improved your fiddle and myObj is created correctly (in table property are rows from both tables). But if you want render this object in json format you have to redesign this object or render the same object in two tables. If you want render two objects with different tables prop you have to convert myObj in to separate objects. Look on my fiddle:
table.forEach((e,i)=>{
let tr_obj = [];
Array.from(e.rows).forEach((ele,ind)=>{
let cells = []
Array.from(ele.cells).forEach((element,index)=>{
let drop_down = $("#drop\\[" + i + "\\]\\[" + ind + "\\]\\[" + index + "\\]").val();
let text_value = $("#text\\[" + i + "\\]\\[" + ind + "\\]\\[" + index + "\\]").val();
cells.push(create_object(drop_down, text_value));
})
tr_obj.push(cells)
});
myObj['table'].push(tr_obj);
});
And fiddle: https://jsfiddle.net/wa3vbsc6/2/
So when I add new rows each row is given an id that increments according the number of rows already added. if I add three rows and then delete the second row, then add another row, now the new row has an id the same as the old third row.
is there an easier way to do this or a loop that i can perform to check for an existing number.
$('body').delegate('.remove', 'click', function() {
$(this).parent().parent().remove();
});
function addnewrow() {
var n = ($('.detail tr').length - 0) + 1;
var tr = '<tr>' +
'<td>' + n + '</td>' +
'<td><select id="drop' + n + '" class="select-service" name="prodService[]"> <
option value = "" > -Choose Service - < /option></select > < /td>'+
'<td id="desc' + n + '"></td>' +
'<td>Delete</td>' +
'</tr>';
Try this way...Put counter outside of the function.
$('body').on("click", '.remove', function() {
$(this).closest("tr").remove();
});
var n = 1;
$('body').on('click', '.add-new-row', function() {
var $tr = $("<tr />");
var $td1 = $("<td />").text(n).appendTo($tr);
var $td2 = $("<td />").append("<select id='drop" + n + "' class='select-service' name='prodService[]' />").appendTo($tr);
var $td3 = $("<td id='desc" + n + "' />").appendTo($tr);
var $td4 = $("<td />").append("<a href='#' class='remove'>Delete</a>").appendTo($tr);
$("table").append($tr);
n++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add-new-row">Add New Row</button>
<table></table>
Using jQuery is nice because you can avoid writing these giant element strings, so I've gone ahead and rewritten your addnewrow() function to (hopefully) make it slightly cleaner.
As far as determining the IDs, while I believe what talg123 suggested in the comments would be fine - storing a global variable that just increases by 1 each time you add a new row - I personally try to avoid polluting the global scope where I can.
You can use this line to find the last drop id, and remove the "drop" text from it so you're just left with a number.
$("tr select").last().attr("id").replace("drop", "");
Unfortunately, this will break if there are no rows becuase it won't be able to find any select elements. So, first we have to check if they exist:
+$("tr select").length ? (exists) : (does not exist)
If it doesn't exist, we'll just use 1.
Put that all together, and you've got:
//If select exists Get last ID and remove "drop" from it, and add 1 Else, 1
$("tr select").length ? 1 + +$("tr select").last().attr("id").replace("drop", "") : 1;
$('body').on("click", '.remove', function() {
$(this).closest("tr").remove();
});
$('body').on('click', '.add-new-row', function() {
var nextId = $("tr select").length ? 1 + +$("tr select").last().attr("id").replace("drop", "") : 1;
//Create a new select list
var $selectList = $("<select id='drop" + nextId + "' class='select-service' name='prodService[]' />");
$selectList.append("<option> -Select Service- </option"); //Append option 1
$selectList.append("<option> Another example </option"); //Append option 2
var $tr = $("<tr />"); //Create a new table row
var $td1 = $("<td />").text(nextId).appendTo($tr); //Create first cell. Set text to nextId. Add it to the row.
var $td2 = $("<td />").append($selectList).appendTo($tr); //Create second cell. Add our select list to it. Add it to the row.
var $td3 = $("<td id='desc" + nextId + "' />").appendTo($tr); //Create third cell. Set its id to 'desc{nextId}'. Add it to the row.
var $td4 = $("<td />").append("<a href='#' class='remove'>Delete</a>").appendTo($tr); //Create fourth cell. Add link to it. Add it to the row.
$("table").append($tr); //Add the row to the table
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add-new-row">Add New Row</button>
<table></table>
I am requesting data from a json to fill a table. I want to limit to 5 the request.
jQuery.getJSON("data/data.json", function(data) {
var table = $("table");
$.each(data, function(id, elem) {
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
});
})
Or another option is to add boolean key "active" to the data and that it brings me the data items with the value = true. How do i do this?
You can use .slice() to filter the returned array down to just the first 5 elements.
data = data.slice(0, 5);
Just use a simple for loop.
var json_arr, limit;
limit = 5; // set limit to whatever you like
json_arr = JSON.parse(json_data);
for(var i = 0; i < limit; i++;) {
var this_item = json_arr[i];
table.append(this_item); // do your thing
}
The best limit you can implement is on your own controller (where you get your data from)
But if you don't have access/don't want to change, you can simple achive this by JavaScript:
var limit = 5; //your Limit
for(var i in data){
if(i > limit) break;
var elem = data[i];
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
}
I have a table that consists of dates across the table headers and fruit down the left hand side. What i'm trying to do is get the date and the fruit eaten from a different object called 'eaten' and plot an X in the table row/column that coincides with the day it was consumed.
HTML
<table class="plan">
<thead>
<tr>
<th><strong>Food</strong></th>
<th>27/01/2017</th>
<th>28/01/2017</th>
<th>29/01/2017</th>
<th>30/01/2017</th>
<th>31/01/2017</th>
<th>01/02/2017</th>
<th>02/02/2017</th>
</tr>
</thead>
<tbody>
<tr><td>Apple</td></tr>
<tr><td>Banana</td></tr>
<tr><td>Carrot</td></tr>
<tr><td>Pear</td></tr>
</tbody>
</table>
The food titles are created via javascript from one object 'food', the dates are generated via momentJS and 'eaten' is the object data I want to plot from.
Javascript
var food = '{"food":[{"Name":"Apple"},{"Name":"Banana"},{"Name":"Carrot"},{"Name":"Pear"}]}';
$.each(JSON.parse(food), function(i, f) {
var tblRow = "";
tblRow += "<tr><td>" + f.Name + "</td></tr>";
$(tblRow).appendTo(".plan tbody");
});
for(i = 7; i > 0; i--) {
var day = moment().subtract('days', i).format('DD/MM/YYYY');
$('<th>' + day + '</th>').appendTo('.plan thead tr');
};
var eaten = '{"eaten":[{"fields":[{"value":"02/02/2017"},{"value":"Carrot"}]},{"fields":[{"value":"31/01/2017"},{"value":"Pear"}]},{"fields":[{"value":"30/01/2017"},{"value":"Banana"}]},{"fields":[{"value":"29/01/2017"},{"value":"Apple"}]},{"fields":[{"value":"27/01/2017"},{"value":"Apple"}]}]}'
What is the best way to go about plotting an X from the eaten object?
Should I get the cellIndex / rowIndex then compare the html text and plot an X?
JSFiddle
My suggestion (without changing your data schema and trying to not change much of your code logic):
parse your JSON once, for further reuse:
var eaten = JSON.parse(eatenJSON);
var food = JSON.parse(foodJSON);
populate a days array with your days.
var days = [];
for(i = 7; i > 0; i--) {
var day = moment().subtract('days', i).format('DD/MM/YYYY');
days.push(day);
}
set data-day and data-food in your td element;
for (var i=0; i<days.length; i++) {
tblRow += "<td data-day='" + days[i] + "' data-food='" + f.Name + "'></td>";
}
iterate over the eaten structure, find the elements with correspondent data-day anddata-food and, set their innerText with X, or whatever you want.
/* fill table */
eaten.eaten.forEach( function(userEaten) {
var fields = userEaten.fields;
var day = fields[0].value;
var food = fields[1].value;
document.querySelectorAll("td[data-day='" + day + "'][data-food='" + food + "']").forEach(function(td) {
td.innerText = "X";
});
});
Working fiddle: https://jsfiddle.net/mrlew/5gj4udf6/1/
EDIT: Updated the fiddle with your new JSON: https://jsfiddle.net/mrlew/5gj4udf6/2/
Just replaced this line
$.each(food, function(i, f) {
with:
food.food.forEach(function(f) {
Problem:
I have a dynamically created HTML table, that is used for filling out time sheets. It is created programmatically - there is no formal control. The design is a mix of CSS with text boxes being created through JavaScript. Now each 'row' of this table is in a class called 'divRow', and is separated from the others by having 'r' and the number of the row assigned to it as the class (i.e 'divRow r1', 'divRow r2', etc.).
Within each of these 'divRow's, I have cells in a class called 'divCell cc'. These do not have any identifiers in the class name. At the very last cell, I have a 'Total' column, which ideally calculates the total of the row and then adds it into a dynamically created text box.
What I have at the moment:
// Function to create textboxes on each of the table cells.
$(document).on("click", ".cc", function(){
var c = this;
if(($(c).children().length) === 0) {
var cellval = "";
if ($(c).text()) {
cellval = $(this).text();
if(cellval.length === 0) {
cellval = $(this).find('.tbltxt').val();
}
}
var twidth = $(c).width() + 21;
var tid= 't' + c.id;
if(tid.indexOf('x17') >= 0){
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' readonly />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
//var getRow = $(this).parent().attr('class'); - this gets the 'divRow r#' that it is currently on.
var arr = document.getElementsByClassName('cc');
var tot = 0;
for(var i = 0; i<arr.length; i++){
if(parseInt(arr[i].innerHTML) > 0){
tot += parseInt(arr[i].innerHTML);}
}
$('#t' + c.id).focus();
$(this).children().val(tot);
}else{
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
$('#t' + c.id).focus();
$('#t' + c.id).val(cellval);
}}
});
As you can see, when the user clicks on the 'divCell cc', it creates a text box if one is not present. If the user clicks on the 17th column ('x17'), then it runs the for loop, and assigns the value of the total to the text box.
What I need to happen:
So what happens now is that the last cell sums the total of each cell that has a value. However, they are not row-dependent. I need it to calculate based on the row that it is currently 'on'. So if I'm calculating the 2nd row, I don't want the sum of the first, second and third being entered into the total, I just want the 2nd rows' values summed.
What I've tried:
I've tried looping through and using the 'divRow r#' number to try and get the items in the array that end in that number. (cells are given an id of 'x#y#' and the text boxes assigned to those cells are given an id of 'tx#y#').
I've tried getting elements by the cell class name, and then getting their parent class and sorting by that; didn't get far though, keep running into simple errors.
Let me know if you need more explanation.
Cheers,
Dee.
For anyone else that ever runs into this issue. I got it. I put the elements by the row class into an array, and then using that array, I got the childNodes from the row class. The reason the variable 'i' starts at 2 and not 0 is because I have 2 fields that are not counted in the TimeSheet table (Jobcode and description). It's working great now.
Cheers.
$(document).on("click", ".cc", function(){
var c = this;
if(($(c).children().length) === 0) {
var cellval = "";
if ($(c).text()) {
cellval = $(this).text();
if(cellval.length === 0) {
cellval = $(this).find('.tbltxt').val();
}
}
var twidth = $(c).width() + 21;
var tid= 't' + c.id;
if(tid.indexOf('x17') >= 0){
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' readonly />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
// Get current row that has focus
var getRow = $(this).parent().attr('class');
// Get the row number for passing through to the next statement
var rowPos = getRow.split('r', 5)[1];
// Get all the elements of the row class and assign them to the rowClass array
var rowClass = document.getElementsByClassName('r' + rowPos)
// Given the rowClass, get the children of the row class and assign them to the new array.
var arr = rowClass.item(0).childNodes
// Initialize the 'total' variable, and give it a value of 0
var tot = 0;
// Begin for loop, give 'i' the value of 2 so it starts from the 3rd index (avoid the Req Code and Description part of the table).
for(var i = 2; i<arr.length; i++){
if(parseInt(arr[i].innerHTML) > 0){
tot += parseInt(arr[i].innerHTML);}
}
// Assign focus to the 'Total' cell
$('#t' + c.id).focus();
// Assign the 'total' variable to the textbox that is dynamically created on the click.
$(this).children().val(tot);
}else{
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
$('#t' + c.id).focus();
$('#t' + c.id).val(cellval);
}}
});