How to make a jQuery table editable for specific column only - javascript

The code I have is below using a simple DataTable . I get the data and all sorting is great but now I want to update the cell contents in last column only which is the "reason not covered" column and submit it back as update to DB possibly by AJAX calls . I am not sure whether to use Editor or JEditable to make the table editable and how to make it editable for that column alone . Have tried different options using makeEditable and Editor but cannot make the inline cell contents editable for column or cell .Have dataTables.editor.min.js in the script path. Also tried jEditable with jquery.jeditable.mini.js Any help deeply appreciated.
jquery-3.1.1.min.js, jquery.dataTables.min.js, dataTables.buttons.min.js, buttons.colVis.min.js, dataTables.editor.min.js
<script>
$(document).ready(function() {
$('#selectedDetails').DataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"fixedHeader": true,
"scrollY": '400px'
});
} );</script>
<table id = "selectedDetails" class="table table-striped table-bordered" cellspacing="0" width="80%">
<caption><h3>DETAILS FOR SELECTED FILTERS: <font color="brown">FORM ID</font>=<font color="blue"><%=request.getAttribute("formNameSelection")%></font> AND <font color="brown">COVERED IN AUTOTAX</font> = <font color="blue"><%=request.getAttribute("YesOrNoValueSelection") %></font> </h3></caption>
<thead style="background-color:#D7DBDD; border:solid 2px; border-color:black">
<tr>
<th>FORM ID</th>
<th>FIELD ID</th>
<th>FIELD NAME</th>
<th>FIELD TYPE</th>
<th>NO: OF HARD CALCS</th>
<th>NO: OF DROP ASSIGNEDS</th>
<th>COVERED IN AUTOTAX ?</th>
<th>REASON NOT COVERED</th>
</tr>
<thead>
</thead>
<tbody>
<c:forEach var="filterFieldInfo" items="${filteredValues}">
<tr>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.formId}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldId}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldName}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldType}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.numHardCalcs}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.numDroptAssigneds}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.autoTaxCovered}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.reasonAutoTaxCovered}" /></td>
</tr>
</c:forEach>
</tbody>
</table>

I made one more. This one, the html is created server side.
Also, it uses a pop over to allow the user to enter in the changes that way.
Like I said, I do not have access to the DataTable Editor library so I used the QTip2 (http://qtip2.com/) library instead.
Click on any cell in the office column.
http://jsbin.com/datecoy/edit?js,output
// Table defintion
$(document).ready(function () {
var dtTable = $('#example').DataTable({
columns: [{ title: "Name" }, { title: "Postition" }, { title: 'Office' }, { title: "Age" }, { title: "Start Date" }, { title: "Salary" }],
columnDefs: [{ targets: [2], className: "editColumn" }]
});
$('#example').on("click", ".editColumn", function () {
var index = $(this).index();
var cols = dtTable.settings()[0].aoColumns;
var colTitle = cols[index].title;
var data = dtTable.rows($(this).closest("tr")).data()[0];
DataTableDialog(this, colTitle, data[2]);
})
});

Here is a very simple one but not my first choice. Because it is content editable, you loose control of the width of the column and end up with some strange looking stuff.
Just click on a cell in the edit column and start typing.
event handlers keep the data object and the table cell in sync.
http://jsbin.com/zizepoh/edit?html,js,output
$(document).ready(function() {
// add editable column data
var dtData = $.map(dataStore.data, function(item){item.contentEdit = ""; return item;});
var dtTable = $('#example').DataTable( {
"data": dtData,
"select":"single",
"columnDefs":[{"targets":[6], render : function(ditem){return "<div contenteditable>" + ditem + "</div>";}}],
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" },
{"data":"contentEdit", "className": "contentEdit"}
],
dom: 'Bfrtip',
buttons: [ 'excelHtml5' ]
});
// Uses key press event handler to keep the associated data object in sync
$("#example").on("keypress", ".contentEdit div", function (){
var rData = dtTable.rows($(this).closest("tr")).data()[0];
rData.contentEdit = $(this).text();
$("#txtFollower").val($(this).text());
});
});

this one is a tad safer and more obvious. it puts in a textbox.
Also, I had to add a bit more to make the excel dump work.
http://jsbin.com/zufesop/3/edit?html,js,output
$(document).ready(function() {
// add editable column data
var dtData = $.map(dataStore.data, function(item){item.contentEdit = ""; return item;});
var dtTable = $('#example').DataTable( {
"data": dtData,
"select":"single",
"columnDefs":[{"targets":[6], render : function(ditem){return "<input type='text' value = '" + ditem +"'/>" ;}}],
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" },
{"data":"contentEdit", "className": ""}
],
dom: 'Bfrtip',
buttons: [
{
extend: 'excelHtml5',
text: 'Save as Excel',
// updates the data before being sent to excel
customizeData: function (a, b, c, d) {
var exd = a.body;
var dtdata = $('#example').DataTable().rows().data();
for (var ii = 0; ii < dtdata.length ; ++ii) {
var cur = dtdata[ii].contentEdit;
exd[ii][6] = cur;
}
}
}
]
});
// Uses key press event handler to keep the associated data object in sync
$("#example").on("keyup", "input[type='text']", function (){
var rData = dtTable.rows($(this).closest("tr")).data()[0];
rData.contentEdit = $(this).val();
$("#txtFollower").val($(this).val());
});
});

Here is something for you to look at.
All of my tables are made from an array data objects in JavaScript. Yours, I think, was made from an html table generated server side.
So, to closer emulate what you are doing I created a table server side and then tried to use my code to update it. It did not work. Below is what I had to do update it.
Basically, the code below uses an event handler that pops up an input box for the user to make the change and then save it. (I left all of that out)
// For my object array, this was all I had to do to update the data.
var dtTable = $($(target).closest("table")).DataTable();
var dtData = dtTable.rows($(target).closest("tr")).data()[0];
dtData.office = $(this).siblings("input").val();
dtTable.rows().invalidate().draw();
When I changed it to a server side table, the code above stopped working (even after changing it to work with array of arrays which server side tables use)
To get it to work, I had to update both the data object and the tables html node so it looked like this:
var columnIndex = $(target).index();
var dtTable = $($(target).closest("table")).DataTable();
var dtData = dtTable.rows($(target).closest("tr")).data()[0];
// here, I updated the data node
dtData[columnIndex] = $(this).siblings("input").val();
// then I updated the html td. Once that was done, it started working for the server side table.
$(target).html(dtData[columnIndex]);
dtTable.rows().invalidate().draw();

THanks a bunch again ! I have modified code with your example to try make it work to see what I am missing , below is the modified script and html . In your example I just needed the Edit and Save button , no functionality needed for Add and Delete. Below still doesn't work , I dont actually see even an edit button . What are the parameters inside the function function (e, dt, bt, config) signify ?
<script>
$(document).ready(function() {
var myTable = $('#selectedDetails').DataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"fixedHeader": true,
"scrollY": '400px',
buttons: [{
text: "Edit", className :"editButton",
extend: "selectedSingle",
action: function (e, dt, bt, config) { editRow(e, dt, bt, config); }
}, {
text: "Save",
extend: "selectedSingle",
action: function (e, dt, bt, config) { saveRow(e, dt, bt, config); }
}
}],
dom: "Btp",
select: "single"
});
var dataObject = myTable.rows().data();
// keep the rows from deselection when you click on a textbox
// this means you have to click between textboxes to change edit rows when more than one is open
$("#selectedDetails").on("click", "input", function (e) { e.stopPropagation(); return false; });
table.on('user-select', function (e, dt, type, cell, originalEvent) {
if ($('#selectedDetails input').length > 0) {
e.preventDefault();
return false;
}
});
});
// Save the selected row (assuming its in edit mode)
function saveRow(e, dt, bt, config) {
var r = dt.rows(".selected").nodes()[0];
// if row is not edit mode, just return.
if ($("input", r).length === 0) { return; }
var d = dt.rows(".selected").data()[0];
var containsText = false;
$(r).children("td").each(function (i, it) {
var di = $("input", it).val();
if (di.length > 0) { containsText = true; }
$(it).html(di);
d[i] = di;
});
if (!containsText) {
alert("This row contains no data and will be removed");
dt.rows(".selected").remove().draw();
}
$(".editButton span").text("Edit");
}
// Puts a row in edit mode
function editRow(e, dt, bt, config) {
var r = dt.rows(".selected").nodes()[0];
if( $("span", bt[0]).text() == "Cancel"){
if($(r).hasClass("newRow")){
dt.rows(".selected").remove().draw();
}
else {
$(r).children("td").each(function (i, it) {
var od = dt.cells(it).data();
$(it).html(od[0]);
});
}
$("span", bt[0]).text("Edit");
return;
}
// if row already in edit mode, just return.
if ($("input", r).length > 0) { return; }
$(r).children("td").each(function (i, it) {
var h = $("<input type='text'>");
h.val(it.innerText);
$(it).html(h);
});
$("span", bt[0]).text("Cancel");
}
</script>
<table id = "selectedDetails" class="table table-striped table-bordered" cellspacing="0" width="80%">
<caption><h3>DETAILS FOR SELECTED FILTERS: <font color="brown">FORM ID</font>=<font color="blue"><%=request.getAttribute("formNameSelection")%></font> AND <font color="brown">COVERED IN AUTOTAX</font> = <font color="blue"><%=request.getAttribute("YesOrNoValueSelection") %></font> </h3></caption>
<thead style="background-color:#D7DBDD; border:solid 2px; border-color:black">
<tr>
<th>FORM ID</th>
<th>FIELD ID</th>
<th>FIELD NAME</th>
<th>FIELD TYPE</th>
<th>NO: OF HARD CALCS</th>
<th>NO: OF DROP ASSIGNEDS</th>
<th>COVERED IN AUTOTAX ?</th>
<th>REASON NOT COVERED</th>
</tr>
<thead>
</thead>
<tbody>
<c:forEach var="filterFieldInfo" items="${filteredValues}">
<tr>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.formId}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldId}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldName}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldType}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.numHardCalcs}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.numDroptAssigneds}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.autoTaxCovered}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.reasonAutoTaxCovered}" /></td>
</tr>
</c:forEach>
</tbody>
</table>

contentEditable anyone?
Says it's new for HTML5, and also a "Global HTML" attribute.
Seems to work pretty well on table cells.

Related

Datatables show the ajax data but blank when I search the data and the data is not listed in info

I am currently having trouble with datatables, when the data is hardcoded int HTML the table is searchable, but when I get from ajax, the data is showed but after I type from search input, the data disappears.
here is the code :
```(function($) {
'use strict';
var responsiveHelper = undefined;
var breakpointDefinition = {
tablet: 1024,
phone: 480
};
// Initialize datatable showing a search box at the top right corner
var initTableWithSearch = function() {
var table = $('#tableWithSearch');
var settings = {
"sDom": "<t><'row'<p i>>",
"destroy": true,
"scrollCollapse": true,
"oLanguage": {
"sLengthMenu": "_MENU_ ",
"sInfo": "Showing <b>_START_ to _END_</b> of _TOTAL_ entries"
},
"iDisplayLength": 5
};
show_list();
table.dataTable(settings);
// search box for table
$('#search-table').keyup(function() {
table.fnFilter($(this).val());
});
}
initTableWithSearch();
function show_list(){
$.ajax({
type : 'ajax',
url : '<?php echo site_url('visi/data_list')?>',
async : true,
dataType : 'json',
success : function(data){
var html = '';
var i;
var no = 1;
for(i=0; i<data.length; i++){
if (data[i].is_deleted == 'n') {
data[i].is_deleted = 'NO';
} else {
data[i].is_deleted = 'YES';
}
html += '<tr>'+
'<td>'+no+'</td>'+
'<td>'+data[i].name+'</td>'+
'<td>'+data[i].detail+'</td>'+
'<td>'+data[i].is_deleted+'</td>'+
'<td style="text-align: right;">'+
'Edit'+' '+
'Delete'+
'</td>'+
'<tr>';
no++;
}
$('#show_data').html(html);
}
});
}
// function
})(window.jQuery); ```
```<table class="table table-hover demo-table-search table-responsive-block" id="tableWithSearch">
<thead>
<tr>
<th>No.</th>
<th>Name</th>
<th>Detail</th>
<th>Deleted?</th>
<th>Action</th>
</tr>
</thead>
<tbody id="show_data">
<!-- <tr>
<td class="v-align-middle semi-bold">
<p>First Tour</p>
</td>
<td class="v-align-middle">United StatesIndia
ChinaAfrica
</td>
<td class="v-align-middle">
<p>it is more then ONE nation/nationality as its fall name is The United Kingdom of Great Britain and North Ireland..</p>
</td>
<td class="v-align-middle">
<p>Public</p>
</td>
</tr> -->
</tbody>
</table>```
the data before
(https://i.stack.imgur.com/34QDA.png)
the data disappears after type on search
(https://i.stack.imgur.com/5r5ne.png)
thank you

How to send multiple rows by selecting checkbox in datatable and send it to controller for update?

I am working in ASP.NET MVC.
I am having a datatable with checkbox options to select multiple rows to send to controller for bulk update. As, I am having two different funtions with two different buttons in same view, I cant able to use Form submission method.
I am trying to send via Ajax method. But, cant able to send selected rows into an array.
Codes that I tried below:
Table:
<table cellspacing="1" cellpadding="2" style="width: 100%;" id="tblStatus" class="table table-striped table-hover table-bordered table-hd">
<thead>
<tr class="gridheader">
<td valign="middle" align="center" style="width: 2%;">
<input id="chkAll" onclick="javascript: checkAll();" type="checkbox" name="chkAll" />
</td>
<td style="width: 25%;" >Data1</td>
<td style="width: 25%;" >Data2</td>
<td style="width: 25%;" >Data3</td>
<td style="width: 25%;" >Data4</td>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var m in Model)
{
<tr>
<td valign="middle" align="center" style="width: 2%;">
<input id="chkBox" name="chkBox" type="checkbox" onclick="javascript: checkManual();" value="" />
</td>
<td>Data1</td>
<td>Data2</td>
<td>Data3</td>
<td>Data4</td>
</tr>
}
}
</tbody>
</table>
Controller:
[HttpPost]
public ActionResult Update(List<StatusVM> data1)
{
return View();
}
Button to Update:
<div class="btn-group">
<button #*type="submit"*# id="btnUpdate" onclick="GetData();" name="btnUpdate" class="btn btn-block btn-success btn-flat"><span class="hide-on-mobile">Update </span><i class="fa fa-save"></i></button>
</div>
Javascript-Where I am trying to send data:
function GetData() {
var table = $('#tblStatus').DataTable();
if ($('[name="chkBox"]:checked').length <= 0) {
alert('Please select minimum one data');
}
else {
var CData = new Array();
var dd;//= $('[name="chkBox"]:checked').toArray();
$('[name="chkBox"]:checked').each(function (data) {
var rowData =table.row(this).data();
CData.push(rowData);
});
$.ajax({
type: "POST",
url: "/Test/Update",
contentType: "application/json;",
headers: { 'RequestVerificationToken': gettoken() },
data: JSON.stringify({ data1: CData }),
});
}
}
How to fix this? I want sent rows data that selected with checkbox only. Kindly help.
From just looking at your javascript, I think your main issue is that you're not mapping the data you're sending to the Controller to the object that the Update Action Method is expecting and so the Model Binding is not working.
For example, say your StatusVM object looked like this:
public class StatusVM
{
public int Id {get;set;}
public string Name {get;set;}
}
In your javascript, you'll need to map the items from your html objects to that object, so create an object that represents it like in the example below:
var cData = new Array();
for(var i = 0; i < rowData.length; i++){
cData.push(obj);
}
function GetData() {
var table = $('#tblStatus').DataTable();
if ($('[name="chkBox"]:checked').length <= 0) {
alert('Please select minimum one data');
}
else {
var CData = new Array();
$('[name="chkBox"]:checked').each(function (data) {
var rowData =table.row(this).data();
var obj = {
Id: rowData.Id,
Name: rowdata.Name
};
CData.push(obj );
});
$.ajax({
type: "POST",
url: "/Test/Update",
contentType: "application/json;",
headers: { 'RequestVerificationToken': gettoken() },
data: CData,
});
}
}
Hope that helps.
As you are creating table("DOM") in your view, row().data() will return "Array" of values of row. In your case it would be like row 1 data will be ["Data1", "Data2", "Data3"...].
In this case you have to make "StatusVM" like object in each function callback
$('[name="chkBox"]:checked').each(function(data) {
var rowData = table.row($(this).parents('tr')).data();
var obj = {
"col1": rowData[0],
"col2": rowData[1],
"col3": rowData[2]
}
CData.push(obj);
});
If you want the row return object then you have to bind DataTable with JSON.
As documentation says:
Data source object for the data source of the row. This will be an array if you use DOM sourced data, otherwise it will be the array / object / instance that is used to populate the table with data.

jQuery sortable serialize not recognizing dynamically added content

I am trying to re-order a list via ajax on sortable update, however after adding a new item to this list via ajax after sortable has already been initialized on page load, it does not recognize the new item with the "serialize" function. It does allow me to drag it around as though it is working, but the code that gets sent with my update function is missing the new element.
//Sort categories
$('#categories-list').find('tbody').sortable({
connectWith: 'tbody',
opacity: 0.6,
cursor: 'move',
forcePlaceholderSize: true,
update: function(e) {
var serialized = $('#categories-list tbody').sortable('serialize');
console.log(serialized);
$.post('admin/ereg_forms/set_category_position', serialized, function(data) {
if (data.status == 'error') {
alert(data.message);
}
});
}
});
//Add category submit
$("#add-category-submit").click(function(e) {
e.preventDefault();
$(".errors-block").html('');
$('#add-category-submit').hide();
$.ajax({
url: $("#add-category-form").attr('action'),
type: 'POST',
data: $('#add-category-form').serialize(),
dataType: 'json',
success: function(data) {
$('#add-category-submit').show();
//Check if server side validation passed
if (data.status == 'error') {
//Show error on popup dialog
$("#add-category-form .errors-block").html(data.message);
alert('Sorry, the information that was sent is invalid. Please review the errors at the top of the form and try again.');
} else {
var category_data = data.data;
var tableRow = '<tr class="category-row-' + category_data.id + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span>' +
'</td><td>' + category_data.title +
'</td><td></tr>'
$(tableRow).appendTo('#categories-list tbody');
resetForm($('#add-category-form'));
//Close popup window
$('#add-category').dialog('close');
$("<div title='Success!'>Category has been saved.</div>").dialog({
modal: true,
width: 'auto'
});
}
},
error: function(data) {
alert('An unknown error has occurred, please try again.');
$('#add-category-submit').show();
}
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<table class="data" id="categories-list">
<thead>
<tr>
<th> </th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr id="category-row-19">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test1</td>
</tr>
<tr id="category-row-20">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test</td>
</tr>
</tbody>
</table>
I have looked everywhere for a solution but have not found one that has worked. I have tried using the "refresh" function with sortable, I have tried initializing sortable inside of the success function of the ajax call to add new categories but it also does not work.
when I console.log(serialized) it only has the originally loaded elements in the array.
IDK what is going on, but this fake add works, perhaps you can emulate this? Note I cleaned up a couple syntax issues and used the ajax promise methods to better organize it.
I suggest you update your jQuery version, some better stuff in more recent versions with bug fixes.
//Sort categories
$('#categories-list').find('tbody').sortable({
connectWith: 'tbody',
opacity: 0.6,
cursor: 'move',
forcePlaceholderSize: true,
update: function(e) {
var serialized = $('#categories-list tbody').sortable('serialize');
console.log(serialized);
// $.post('admin/ereg_forms/set_category_position', serialized, function(data) {
// if (data.status == 'error') {
// alert(data.message);
// }
// });
}
});
$('#addmorefool').on('click', AddMore);
function AddMore() {
let tbody = $('#categories-list').find('tbody');
let rowscount = tbody.find('tr').length;
let newRow = '<tr id="category-row-' + rowscount + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td><td class="category-row-title">test' + rowscount + '</td></tr>';
tbody.append(newRow);
}
AddMore();
//Add category submit
$("#add-category-sumbit").on('click', function(e) {
//console.log("howdy");
e.preventDefault();
var myform = $("#add-category-form");
var errorBlock = myform.find(".errors-block");
errorBlock.html('');
errorBlock.dialog({
modal: true,
width: 'auto',
autoOpen: false
});
var catSub = $('#add-category-submit');
catSub.hide();
var myjax = $.ajax({
url: myform.attr('action'),
type: 'POST',
data: myform.serialize(),
dataType: 'json'
})
.done(function(data) {
catSub.show();
//Check if server side validation passed
var category_data = data.data;
var tableRow = $('<tr class="category-row-' + category_data.id + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span>' +
'</td><td>' + category_data.title +
'</td><td></tr>');
let tbody = $('#categories-list').find('tbody');
tbody.append(tableRow);
resetForm(myform);
//Close popup window (out cause have none)
//('#add-category').dialog('close');
$("<div title='Success!'>Category has been saved.</div>").dialog({
modal: true,
width: 'auto'
});
}).fail(function(data) {
//Show error on popup dialog
errorBlock.html('<span>Sorry, the information that was sent is invalid. Please review the errors at the top of the form and try again.</span>' + data.message);
errorBlock.dialog("open");
//catSub.show(); (out cause not in code)
});
});
tr td {
border: 1px solid lime;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div id="add-category-form" action="metoo">I am an empty form, so what
<div class="errors-block">me error aggain? no way</div>
</div>
<table class="data" id="categories-list">
<thead>
<tr>
<th> </th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr id="category-row-19">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test1</td>
</tr>
<tr id="category-row-20">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test</td>
</tr>
</tbody>
</table>
<button id="addmorefool" type="button">Add More</button>
<div class="errors-block">me error</div>
<button type="button" id="add-category-sumbit">add category</button>
I ended up solving this problem, the issue was in the add category function I was applying the "class" attribute instead of using the "id" attribute for the category-row-{id}.

Datatables child rows form

I am using this example but within the child rows, I have a form. The problem is, it's not submitting the input from the child rows if the child rows are closed. Now I see datatables is using: show() and hide() functions as in this code of their example:
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
Now that makes me think it's just hiding it and showing it so when its hidden, it should still be there AND submitted, but it isn't since they are probably using a datatables made function or something. How would I make it that I can actually submit the input fields in the child rows when the child rows are "hidden"? It works fine when I have the row opened.
Unfortunately JQuery DataTables doesn't provide any method to get the informations that you need, moreover it removes the hided rows from the DOM.
So, the only thing you could do is to store the modified values in detail rows in some variable and read them on submit, see following please:
var dataSet = [
{
"id" : 1,
"name" : "Tiger Nixon",
"position" : "Edinburgh",
"salary" : "5421"
},
{
"id" : 2,
"name" : "Ludovico Moro",
"position" : "Milan",
"salary" : "8670"
},
{
"id" : 3,
"name" : "Julio Iglesias",
"position" : "Madrid",
"salary" : "12500"
}
];
var fullnames = [];
$(document).ready(function() {
var table = $('#example').DataTable( {
"data": dataSet,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td><input type="text" class="fullname" id="' + d.id + '" value="' + d.name + '" onchange="javascript:inputChange(this.id, this.value)"></td>'+
'</tr>'+
'</table>';
}
$("#form1").submit(function( event ) {
$.each(fullnames, function(index, value){
if(fullnames[index]){
console.log("Modified record " + index + ", new value is: " + value);
}
});
event.preventDefault();
});
function inputChange(id, val){
fullnames[id] = val;
}
td.details-control {
background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.6/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.6/css/jquery.dataTables.min.css" rel="stylesheet"/>
<form id="form1">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
<input type="submit">
</form>
To sum up:
1) Declare a global var to store the fullnames
var fullnames = [];
2) In the function format, add onchange listener to the input box
onchange="javascript:inputChange(this.id, this.value)"
3) Create the listener
function inputChange(id, val){
fullnames[id] = val;
}
4) Finally, read its values on submit
$.each(fullnames, function(index, value){
if(fullnames[index]){
console.log("Modified record " + index + ", new value is: " + value);
}
});
Obviously instead of a fullnames array you can save an array of objects containing all the fields you need.
I hope it helps you, bye.

DataTables (JQuery) on how to multi column filter text box given a array that contain the data?

I am trying to do a multi column filter as shown in this page (http://www.datatables.net/examples/api/multi_filter.html) using a array that contain all the data (called 'my_array_data') but I could not get those filter text box displayed.
Below is the code:
<script type="text/javascript">
var asInitVals = new Array();
$(document).ready(function() {
$('#dynamic').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
var oTable = $('#example').dataTable( {
"aaData": my_array_data,
"bProcessing": true,
"bAutoWidth": false,
"fnInitComplete": function() {
var oSettings = this.fnSettings();
for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ){
if(oSettings.aoPreSearchCols[i].sSearch.length>0){
$("tfoot input")[i].value = oSettings.aoPreSearchCols[i].sSearch;
$("tfoot input")[i].className = "";
}
}
},
"aoColumns": [
{
"sTitle": "From",
"sClass": "center",
"sWidth": "10%"
},
{
"sTitle": "To",
"sClass": "center",
"sWidth": "10%"
},
{
"sTitle": "Note",
"sClass": "center",
"sWidth": "80%"
}
]
} );
$("tfoot input").keyup( function () {
/* Filter on the column (the index) of this element */
oTable.fnFilter( this.value, $("tfoot input").index(this) );
} );
/*
* Support functions to provide a little bit of 'user friendlyness' to the textboxes in
* the footer
*/
$("tfoot input").each( function (i) {
asInitVals[i] = this.value;
} );
$("tfoot input").focus( function () {
if ( this.className == "search_init" )
{
this.className = "";
this.value = "";
}
} );
$("tfoot input").blur( function (i) {
if ( this.value == "" )
{
this.className = "search_init";
this.value = asInitVals[$("tfoot input").index(this)];
}
} );
});
For your info: I do not have a <table> ... </table> as mention before that I store my data in the array called ''my_array_data' and therefore do not have <input class="search_init"/>. Also, "my_array_data" contain three column - basically named as - "From", "To", and "Note".
Any Insight in getting 3 columns of search filter for my array "my_array_data"?
Appreciate any help offer.
#Anderson Karu yeah here is the sample for individual column filter above to header
goto herehttp://jsfiddle.net/s8F9V/1/
You need to define those 3 text boxes on your markup. Here's a shortened example of how I currently achieve the same thing using datatables:
<table id="example">
<thead>
<tr>
<th class="theader">
Date
</th>
<th class="theader">
Delay
</th>
<th class="theader">
Status
</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th class="centered">
<input type="text" id="id1" name="id1" class="search_init" />
</th>
<th class="centered">
<input type="text" id="id2" name="id2" class="search_init" />
</th>
<th class="centered">
<input type="text" id="id3" name="id3" class="search_init" />
</th>
</tr>
</tfoot>
</table>
And my initialization code is something like:
var oTable = $("#example").dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"iDisplayLength": 10,
"bSortClasses": false,
//...etc etc
});
$("tfoot input").keyup(function(event) {
/* Filter on the column (the index) of this element */
if (event.keyCode == 13)//only on enter pressed
{
var colIndex = getColumnIndex(this.id);//this is a custom function I wrote. Ignore it
oTable.fnFilter(this.value, colIndex);
}
});

Categories

Resources