Jquery: Inline editing for tables inner rows - javascript

I am new to jquery and datatable.
I have developed the editable datatable for "contacts", where each row represents a contact.
Each "contact" has some "actions" associated with them.
When the user clicks on a particular "contact" the associated "actions" are displayed as additional rows under that particular contact.
Now I want to make both the "contact" row and the "action" rows editable. I have used "jEditable" plugin and can get the "contact" row as editable and not the "action".
Any idea, or help will be greatly appreciated.
userInfo = "<table id='mycontacttable'><thead><tr><th></th><th>FirstName</th><th>FamilyName</th></tr></thead><tbody> ";
/*constructing the Contact table, at this stage without the actions.*/
for(i =0 ; i < response.result.length ; i++){
var contactid=response.result[i].contactID;
userInfo += "<tr><td>"+
"<img src=\"../javascript/datatables/media/images/details_open.png\" rel="+contactid+" alt=\"expand/collapse\"></td>"+
"<td>"+ response.result[i].givenName + "</td><td>" + response.result[i].familyName+"</td></tr> ";
}
userInfo += "</tbody></table> ";
$('#info').html("The following are your contacts. " + userInfo);
/*setting the sortable and unsortable columns*/
oTable= $('#mycontacttable').dataTable({
"iDisplayLength": 25,
"bSort": true,
"aoColumns": [
{ "bSortable": false },//Disable sorting on this column
null,
null
]
}).makeEditable();
/*clicking a particular row in the table mycontacttable, and assigning the click event*/
$('#mycontacttable tbody td img').live("click",function () {
var nTr = this.parentNode.parentNode;
if (this.src.match('details_close')) {
/* This row is already open - close it */
this.src = "../javascript/datatables/media/images/details_open.png";
oTable.fnClose(nTr);
}
else {
/* Open this row */
this.src = "../javascript/datatables/media/images/details_close.png";
var contact_id = $(this).attr("rel");/*contact id of a particular row that is clicked is stored in the variable contact_id*/
/*creating a sub table*/
action_sub_table = "<table id='submycontacttable'>"
for(i =0 ; i < response.result.length ; i++){
var contactid=response.result[i].contactID;
if(contact_id==contactid){
/*Iterating through each action of the contact, and constructing a sub table row for it*/
for(count=0;count<response.result[i].actionSet.length;count++){
action_sub_table += "<tr><td>"+response.result[i].actionSet[count].actionID+" </td><td>"+
response.result[i].actionSet[count].actionDueDate+"</td><td>" +
response.result[i].actionSet[count].actionNote+"</td></tr>";
}
}
}
action_sub_table +="</tablr>"; /*Construction of the subtable complete*/
oTable.fnOpen(nTr, action_sub_table, "info_row" );
}
});

you can try jqGrid instead, I suppose that would be perfect in your case http://www.trirand.com/blog/

Related

Buttons in the first column disappear when sorting the table

I have a datatable that shows mock json data retrieved from a text file. I have removed the first column as it contains the id and it isn't ideal to display the id on the table. I appended a buy button on each row on the first column only. However, when I sort the table the button disappears and the original first column data also appears.
JavScript:
$(document).ready(function() {
$.getJSON('/apps/mchp/clientlibs/clientlib-site/components/parametrictable/data.txt', function(json) {
var data = json.data;
var $thead = $('#parametrictable').find('thead');
var tr = $("<tr>");
$thead.append(tr);
var columns = [];
var obj = Object.keys(data[0]);
console.log(data[0])
var button = '<div class="left-btn"><i class="download fas fa-file-download"></i></div><div class="right-btn"><div class="input-group"><div class="input-group-area"><input type="text" value="100"></div><div class="input-group-icon">BUY</div></div></div>';
$.each(data[0], function(name, value) {
var column = {
"data": name,
"title":name
};
$('tr').find('th:first-child',).remove();
columns.push(column);
});
for (i=1; i<obj.length; i++) {
$(".dropdown-content").append('<li><input type="checkbox" class="dropcheck" data-column="'+i+'"/>'+obj[i]+'</li>');
}
var table= $('#tableId').DataTable({
data: data,
columns: columns,
columnDefs: [ {
orderable: true,
className: 'select-checkbox',
targets: 1
} ],
select: {
style: 'multi',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]]
});
$('tr').find('th:first-child').remove();
$('tr').find('td:first-child').remove();
$('tr').find('td:first-child').append(button);
$('tr').on('change', function(e){
e.preventDefault();
console.log('change!');
});
$('input[type=checkbox]').on( 'change', function (e) {
e.preventDefault();
var column = table.column( $(this).attr('data-column') );
column.visible( ! column.visible() );
} );
$('.show-all').on( 'click', function (e) {
e.preventDefault();
var obj = Object.keys(data[0])
for (i=1; i<obj.length; i++) {
var col = table.columns([i]);
if (col.visible().join(', ') == 'false') {
col.visible(true);
$(".dropcheck").prop("checked", false);
}
}
} );
});
})
First, it is not a good practice to hide datatable columns by .remove(), datatables have a built-in code for that by columnDefs refer:
https://datatables.net/examples/basic_init/hidden_columns.html
Second, that is not the right way to append data/html in datatable columns, use rowCallback function for datatable, see:
columnDefs: [
{
"targets": [ 0 ],
"visible": false,
"searchable": false
},
],
rowCallback: function(row, data, index) {
if($('td:eq(1)', row).find('.download').length == 0)
{
$('td:eq(1)', row).append(button);
}
},
When using datatable sort or search or any datatable actions it always refreshes the table therefore, any initialization before the action will be disregarded unless executed again.

How to apply the condition in javascript that row has been filled?

Actually I am retrieving some data from database through ajax and on retrieval of data i made some dynamic element in html using javascript. I made dynamic row in a container and in that row i making a dynamic div whose class is "col-md-4" it means there can be atleast 3 divs in a dynamic .... Now no. of divs whose class is col-md-4 depends upon the rows retrieved from database it means everytime when data is retrieved there will be a new row in which a new div will form with only div col-md-4. Now i want there should be 3 divs of class-md-4 should be created then new should be created
$.ajax({
url: '../php/admin/upcoming_match.php',
type: 'post',
data: {},
success: function(response) {
var n=1;
var data = JSON.parse(response);
if(data!=''){
$.each(data, function(i, item) {
var parent= document.getElementsByClassName('carousel')[0];
var row1= document.createElement("div");
row1.setAttribute("class","row");
row1.setAttribute("id","row"+n);
parent.appendChild(row1);
var child=document.getElementbyId('row'+n);
var crow1= document.createElement("div");
crow1.setAttribute("class","col-md-4");
crow1.setAttribute("id",data[i].id);
row1.appendChild(crow1);
n++;
return n;
});
}
}
});
In this code the new dynamic will have only one child div ... i want should have atleast 3 child divs. For e.g, if we retrieved 4 rows from database then there should a new dynamic row which should have 3 child divs that contain the data of 3 rows then there should be a new row which should 4th child div row but in my present if i retrieve 4 rows then 4 news row class are formed which contain a child div that contain the data of each row retrieved from database
What about something like this ?
It would be easier to have demo data. You can upvote or accept if you like that.
var ajax = prompt('Confirm demo or paste AJAX data', '[ {"id":1}, {"id":2}, {"id":3}, {"id":4}, {"id":5}, {"id":6}, {"id":7}, {"id":8}, {"id":9}, {"id":"A"} ]');
display(ajax);
function display(response) {
var n=1;
var data = JSON.parse(response);
if(data.length) {
for(var i=0;i<data.length;i++) {
var parent= document.getElementsByClassName('carousel')[0];
var row1= document.createElement("div");
row1.setAttribute("class", "row");
row1.setAttribute("id", "row"+n);
parent.appendChild(row1);
var crow1;
for(var j=0;j<3 && i+j < data.length;j++) {
crow1 = document.createElement("div");
crow1.setAttribute("class", "col-md-4");
crow1.setAttribute("id", data[i+j].id);
crow1.innerText = "data" + (i+j) + " id" + data[i+j].id;
row1.appendChild(crow1);
}
i += 3-1;
n++;
}
}
}
DIV.col-md-4 {
display: inline;
background-color: #FF0080;
margin: 5px;
}
.row {
display: block;
background-color: #80E080;
padding: 3px;
}
<div class="carousel">
</div>

Jquery Datatables : How to get row.data when click the the button in one column?

[![enter image description here][1]][1]i have a nested table , I want to having button to generate the row data to info.php by post method (looks like info.php?user = data[0] & key2 = data2) in one column for each row ,
I have one button but I need one button and perform some MySql when they are clicked to get the row data .
when click the button will get to every columns data in the row and post these data to info.php and view in popup window,
How can I perform post the row data in the nested datatable to other php using the button?
my code
click the button ,cannot get the row data ?
$('#example tbody').on( 'click', 'button', function () {
var index = $(this).closest('tr').index();
var data = table.row( $(this).parents('tr') ).data();
alert("References is "+ data[0] +"and section is "+ data[ 1 ]+ " and Stature Titles is "+data[2] );
} );
-UPDATED
just add class for button class='button-info'
columns:[
{ data:'name' },
{ data:'position' },
{ data:'salary' },
{
"targets": -1,
"data": null,
"defaultContent": "<button class='button-info'>Click Me!</button>"
}
]
first assign index value for every parent row
$("table tbody tr").each(function(index) {
$(this).attr('index', index);
})
then add new event for click event of that button and get the parent tr index
just get the index of your selected parent row using data attribute "index" added above
var parent = $(this).closest('table').parents('tr').index();
var parentIndex = $('tbody tr:nth-child('+(parent)+')').attr('index');
and to get your current row in nested data
var index = $(this).closest('tr').index();
so this is the final
$('table').on( 'click', 'td .button-info', function () {
var parent = $(this).closest('table').parents('tr').index();
var parentIndex = $('tbody tr:nth-child('+(parent)+')').attr('index');
var currentIndex = $(this).closest('tr').index();
var data = sections[parentIndex][currentIndex];
console.log(data);
return;
window.open("/info.php?name=" + data.name + "&sal=" + data.salary);
} );
See this updated JSFiddle

How retrieve details of table element clicked?

I have a table and I want retrieve a item details of a element that i sesect:
var tableArtConNom=sap.ui.core.Core().byId("artSnzNomDetail").byId("tableArtConNom");
tableArtConNom.attachItemPress(this.handleRowPress);
tableArtConNom.setModel(new sap.ui.model.json.JSONModel(p_oDataModel));
tableArtConNom.destroyColumns();
tableArtConNom.removeAllColumns();
console.log(tableArtConNom.getColumns());
for(var i=0; i<tableArtConNom.getModel().getProperty("/cols").length; i++){
tableArtConNom.addColumn(new sap.m.Column("colonna"+i, { header: new sap.m.Label({ text: tableArtConNom.getModel().getProperty("/cols")[i] })}));
}
tableArtConNom.destroyItems();
tableArtConNom.removeAllItems();
tableArtConNom.bindAggregation("items", "/items", new sap.m.ColumnListItem({
cells: tableArtConNom.getModel().getProperty("/cols").map(function (colname) {
return new sap.m.Label({ text: "{" + colname + "}" });
}),
type:"Navigation"
}));
if(this.byId("idCodNomDog").getProperty("text")!=""){
var buttonAccept=this.byId("idButtonAccept");
buttonAccept.setProperty("visible", true);
}else{
var buttonAccept=this.byId("idButtonAccept");
buttonAccept.setProperty("visible", false);
}
tableArtConNom.setModel(new sap.ui.model.json.JSONModel(p_oDataModelFull), "fullDataModel");
},
To do it I capture the press event but I find only a number of item:
//IF CLICK ON ROW
handleRowPress : function(evt){
var selectedRowNum = evt.getSource().indexOfItem(evt.getParameter("listItem"));
console.log(selectedRowNum);
},
How can I print the other detailx (for example the content of a column?)
p.s. I can't parse the model of all my rows because in the table I filter the data and the index that i clicked not match by the position in the total model.
in your event handler, use :
var oItem = evt.getParameter("listItem").getBindingContext().getObject();
//NB: if using standard sap.ui.table.Table, use:
//var oItem = evt.getSource().getBindingContext().getObject();
console.log(oItem); //prints the JSON for your selected table row

Duplicate autodividers when selecting from sqlite - jQuery mobile

transaction.executeSql('SELECT * FROM Table1 ORDER BY date DESC', [],
function(transaction, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
$('#records').append('<li date = "'+row['date']+'" data-rowid2="' + row['Id'] + '">' + 'test: ' + row['column1'] + '</li>').trigger('change');
}
}
},errorHandler);
transaction.executeSql('SELECT * FROM Table2 ORDER BY date DESC', [],
function(transaction, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
$('#records').append('<li date = "'+row['date']+'" data-rowid="' + row['Id'] + '">'+ 'Test2: ' + row['column1'] +'</li>').trigger('change');
}
$("#records").listview().listview("refresh");
}
},errorHandler);
},errorHandler,nullHandler);
This is some code which selects columns from 2 different tables. The tables have two different columns called date which stores the date input. Notice the date attribute assigned to the li elements. My problem comes here:
$(document).on("pageinit", "#mypage", function(){
$("#records").listview({
autodividers: true,
autodividersSelector: function (li) {
var out = li.attr("date");
return out;
}
}).listview("refresh");
});
Now since the dates are from two different tables, two autodividers are being created even if they share the same date. For example if table1 date column had 2014-01-02 and table2 date column had 2014-01-02, two separate dividers would be created for the same date and the list elements wouldn't be shown under one. Is there a solution to this problem?
NOTE: Both the select statements append results to the same listview, they are just from different tables
EDIT: I think I have found what the issue is, but I am not sure on how to solve it. Basically, when I append those list elements, Table1 stuff takes priority and always goes first. For example if I had the list like this:
Table 1 item
Table 2 item
Then if I added another Table 1 item it will do this:
Table 1 item
Table 1 item
Table 2 item
Which is displacing the table 2 item from its original position. Is there anyway to solve this?

Categories