Redrawing data table causes data lost - javascript

I've a test case where I need to reload table rows when the user changes input fields and clicks submit button. When the table is first initialized, table body is empty. And then I make a ReST call to get the JSON data and construct the tbody html. Problem I'm facing is that one of the column in the table is supposed to be visible. But since the html markup is being created after the table is initiated, the column that is supposed to be hidden is showing up. I tried to call the draw() function on the table API but that is causing the data to be lost. Is there any other way I can do this?
HTML
<p>
<input type="text" name="startDate" id="startDate"/><br/>
<input type="text" name="endDate" id="endDate"/><br/>
<button type="button" id="refresh">Refresh</button>
</p>
<table id="myTable" style="width: 400px;">
<thead>
<tr>
<th class="no-show">Col A</th>
<th>Col B</th>
<th>Col C</th>
<th>Col D</th>
<th>Col E</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Script
<script type="text/javascript">
var table;
$(document).ready(function(){
var table = $("#myTable").dataTable({
"paging": true,
"pageLength": 5,
"pagingType": "simple",
"info": false,
"order": [[2, "desc"]],
"aoColumnDefs":[
{"aTargets": ["no-show"], "bVisible": false}
],
"fnInitComplete": function(oSettings, json){
$(".dataTables_filter, .dataTables_length").hide();
}
});
refreshTable(table);
$("#refresh").on('click', function(){
refreshTable(table)
});
});
function refreshTable(table)
{
var data = "startDate="+$("#startDate").val()+"&endDate="+$("#endDate").val();
var url = "data.json";
$.ajax({
url: url,
type: "GET",
async: false,
data: data,
success: function(data){
var tbodyHtml = "";
for(var i=0; i< data.length ; i++)
{
tbodyHtml += "<tr>";
tbodyHtml += "<td class='no-show'>"+data[i].eid+"</td>";
tbodyHtml += "<td>"+data[i].firstName+"</td>";
tbodyHtml += "<td>"+data[i].lastName+"</td>";
tbodyHtml += "<td>"+data[i].department+"</td>";
tbodyHtml += "<td>"+data[i].manager+"</td>";
tbodyHtml += "</tr>";
}
$("#myTable tbody").html(tbodyHtml);
table.api().draw();
}
});
}
</script>
P.S. the tbody html I've here is pretty basic. I actually have to do a bit of logic on the data before populating the table. That's why I didn't use Datatable's in built AJAX api.

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

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}.

How can I store input field value within a variable which is inside the td tag in jquery?

I append a html table using ajax. Here, I show two value and create one input field. But now i want to take this input field value within a variable and want to show by alert tag. This input field under td tag and i also set a Id in the input field. In a short word, I just take the input value from appending td and store in lval.Code is given below:
table html code:
<div class="row">
<table id="myTable" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Tag Location</th>
<th>Tag Description</th>
<th>Log Value</th>
</tr>
</thead>
<tbody id="tableBody"></tbody>
</table>
</div>
Jquery and Ajax Code:
<script>
$(document).ready(function () {
$("#myTable").hide();
var logArray = new Array();
var lval=0;
$("#catId").change(function () {
var catId = $("#catId").val();
$("#myTable").show();
var json = { catId: catId };
$.ajax({
type: "POST",
url: '/SaveLogMaster/GetTagMasterByCatId',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function (data) {
$.each(data, function (key, value) {
$("#tableBody").append('<tr><td>' + value.TagLocation + '</td><td>' + value.TagDescription + '</td><td><input type="text" id="lValue" name="LogValue" /></td></tr>');
lval= $("lValue").val(); // not works.. what i use here
alert(lval);
});
}
});
});
});
controller code:
public JsonResult GetTagMasterByCatId(int catId)
{
return Json(aSaveLogMasterManager.GetTagMasterData(catId));
}

How to link esimakin pagination with my table?

I am trying to use the esimakin jQuery Pagination plugin to break my table up into multiple pages because it is getting its data from an ever growing database. However my pagination bar does not:
Split table into pages
Change pages when I click next or previous.
Any advice would be much appreciated.
HTML:
<div class="table-responsive">
<div class="form-group pull-right">
<input type="text" id="myInput" onkeyup="filterTable()" class="search form-control" placeholder="Filter Table">
</div>
<div class="form-group pull-left">
Load Selected
</div>
<table id="draftTable" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th data-field="radio"></th>
<th data-field="bulletin_id">Bulletin ID</th>
<th data-field="event">Event</th>
<th data-field="badge_num">Badge Number</th>
<th data-field="AYEAR">Year</th>
</tr>
<tbody>
</tbody>
</thead>
</table>
</div>
<ul id="pagination" class="pagination-sm pull-right"></ul>
</div>
</div>
JS:
<script>
$(document).ready(function(){
populateTables('S');
});
function populateTables(res){
console.log(res)
$.getJSON("bulletinListJSON.asp", {res:res}, function(data){
}).done(function( data ) {
for (var i=0;i<=data.length;i++){
var draftData = "<tr><td><input type=radio value="+ i + " name=load id=load /></td><td>" + data[i].BULLETIN_ID + "</td><td>" + decodeURIComponent(data[i].EVENT) + "</td><td>" + data[i].BADGE_NUM + "</td><td>" + data[i].AYEAR + "</td></tr>";
$('#draftTable').find('tbody').append(draftData);
}
});
}
function filterTable(event) {
var filter = event.target.value.toUpperCase();
var rows = document.querySelector("#draftTable tbody").rows;
for (var i = 0; i < rows.length; i++) {
var firstCol = rows[i].cells[1].textContent.toUpperCase();
var secondCol = rows[i].cells[2].textContent.toUpperCase();
var thirdCol = rows[i].cells[3].textContent.toUpperCase();
var fourthCol = rows[i].cells[4].textContent.toUpperCase();
if (firstCol.indexOf(filter) > -1 || secondCol.indexOf(filter) > -1 || thirdCol.indexOf(filter) > -1 || fourthCol.indexOf(filter) > -1) {
rows[i].style.display = "";
} else {
rows[i].style.display = "none";
}
}
}
document.querySelector('#myInput').addEventListener('keyup', filterTable, false);
$("#draftTable tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:second').html();
alert(value);
});
$('.ok').on('click', function(e){
alert($("#table tr.selected td:first").html());
});
//Pagination
$('#pagination').twbsPagination({
totalPages: 35,
visiblePages: 7,
items: 20,
itemOnPage: 8,
});
</script>
search in google:
jq dataTables
Wery nice table.
Search, Download (Excel, word, pdf), order column, server side or cliend side run, more more....
İm use this. 15 million rows.
The twbs-pagination plugin provides an onPageClick callback option; you'll need to implement that.
You could also dynamically set the total number of page based on the length of the response data.
A snippet from a simple gist based on your situation.
function setContent( page ) {
// generate markup to display
$('#page-content').html(data[page]);
}
$('#pagination').twbsPagination({
totalPages: data.length, // from $.ajax response
visiblePages: 7,
onPageClick: function (event, page) {
setContent(page);
}
});

How to make a jQuery table editable for specific column only

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.

Categories

Resources