datatable append html but got refreshed? - javascript

Not sure what is wrong, for me my code has the right logic. But somehow the html didn't stay after 2nd click onward. I expect my custom html would appear after the newly added tr.
my function
function appendRow(name, position, office, age, date,salary) {
var t = $('#example').DataTable();
var node = t.row.add([
name,
position,
office,
age,
date,
salary,
]).draw().node();
var detail_row = '';
detail_row = '<h3>Custom HTML</h3>';
$(node).addClass('result-row');
node = node.outerHTML += detail_row;
$(node).hide().fadeIn('normal');
}
https://jsfiddle.net/282w8yfk/

it is happening in this way because you applied sorting on the name column, so datatable being quite smart it adds the row where it needs to be... so if you want to add that in the last remove sorting option on name column...
and here is a small code change:
$(document).ready(function() {
/* Formatting function for row details - modify as you need */
function format(d) {
console.log(d);
// `d` is the original data object for the row
return '<table cellpadding="4" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Name:</td>' +
'<td>' + d[0] + '</td>' +
'</tr>' +
'<tr>' +
'<td>Full Name:</td>' +
'<td>' + d[4] + '</td>' +
'</tr>' +
'<tr>' +
'<td>Extra info:</td>' +
'<td>And any further details here (images etc)...</td>' +
'</tr>' +
'</table>';
}
var table = $('#example').DataTable({
"columnDefs": [{
"targets": [4],
"visible": false,
"searchable": false
}]
/* the problem is here, it won't work if I enable sorting*/
});
function appendRow() {
var t = $('#example').DataTable();
var node = t.row.add([
"James Bond",
"Spy", "55", "$9000", "James Bond Larry"
]).draw().node();
console.log(node);
$(node).addClass('result-row').hide().fadeIn('normal');
};
$('#add').click(function() {
appendRow();
});
$('#example tbody').on('click', '.result-row', 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');
}
});
});
reference 1 - sort
reference 2 - row.add

Related

build unique table with JQuery AJAX

I have a script that builds a table and makes it editable once the user clicks on a cell. The User then leaves a comment and it will update the JSON file as well as the HTML table.
The problem I am having is that if I have two tables with separate JSON files, how can I implement the same script on both of the tables? Would I have to have two separate scripts for each table? How can I do it based off the ID of the table
JSON1:
[{"GLComment":"comment from table 1","EnComment":""},
{"GLComment":"","EnComment":""}]
JSON2:
[{"GLComment":"comment from table 2","EnComment":""},
{"GLComment":"","EnComment":""}]
I have tried doing this to append to my existing table
var tblSomething = document.getElementById("table1");
<table class="table 1">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
//table does not get built here only for table 1
<table class="table 2">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
<script>
//this only works for table1
$(document).ready(function() {
infoTableJson = {}
buildInfoTable();
});
function buildInfoTable(){
$.ajax({ //allows to updates without refreshing
url: "comment1.json", //first json file
success: function(data){
data = JSON.parse(data)
var tblSomething = '<tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td data-key="' + key + '">' + value + '</td>';
});
//tblSomething += '<td><button class="editrow"></button></td>'
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('.table').append(tblSomething)
$('.table td').on('click', function() {
var row = $(this).closest('tr')
var index = row.index();
var comment = row.find('td:nth-child(1)').text().split(',')[0]
var engcomment = row.find('td:nth-child(2)').text().split(',')[0]
var temp1 = row.find('td:nth-child(1)').text().split(',')[0]
var temp2 = row.find('td:nth-child(2)').text().split(',')[0]
var newDialog = $("<div>", {
id: "edit-form"
});
newDialog.append("<label style='display: block;'>GL Comment</label><input style='width: 300px'; type='text' id='commentInput' value='" + comment + "'/>");
newDialog.append("<label style='display: block;'>Eng Comment</label><input style='width: 300px'; type='text' id='engInput' value='" + engcomment + "'/>");
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Edit',
height: 350,
width: 350,
modal: true,
autoOpen: false,
buttons: [{
text: "Save",
click: function() {
console.log(index);
user = $.cookie('IDSID')
var today = new Date();
var date = (today.getMonth()+1)+'/'+today.getDate() +'/'+ today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
//FIXME
var comment = newDialog.find('#commentInput').val() + ", <br> <br>" + dateTime + " " + user;
var engcomment = newDialog.find('#engInput').val() + ", <br><br>" + dateTime + " " + user; //it updates both of them no
row.find('td[data-key="GLComment"]').html(comment) //this is what changes the table
row.find('td[data-key="EngComment"]').html(engcomment) //this is what changes the table
// update data
data[index].GLComment = comment;
data[index].EngComment =engcomment;
$.ajax({
type: "POST",
url: "save.asp",
data: {'data' : JSON.stringify(data) , 'path' : 'comments.json'},
success: function(){},
failure: function(errMsg) {
alert(errMsg);
}
});
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
}
</script>
The "key" here is prebuilt table... And that is a good job for the jQuery .clone() method.
$(document).ready(function() {
// call the function and pass the json url
buildInfoTable("comment1.json");
buildInfoTable("comment2.json");
// Just to disable the snippet errors for this demo
// So the ajax aren't done
// No need to run the snippet :D
$.ajax = ()=>{}
});
function buildInfoTable(jsonurl){
$.ajax({
url: jsonurl,
success: function(data){
data = JSON.parse(data)
// Clone the prebuild table
// and remove the prebuild class
var dynamicTable = $(".prebuild").clone().removeClass("prebuild");
// Loop the json to create the table rows
$.each(data, function(idx, obj){
rows = '<tr>';
$.each(obj, function(key, value){
rows += '<td data-key="' + key + '">' + value + '</td>';
});
rows += '</tr>';
});
// Append the rows the the cloned table
dynamicTable.find("tbody").append(rows)
// Append the cloned table to document's body
$("body").append(dynamicTable)
}
})
}
</script>
/* This class hides the prebuid table */
.prebuild{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This table is a "template" It never will be used but will be cloned -->
<table class="prebuild">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
<tbody>
</tbody>
</table>

how to get the value of the clicked table row?

My question is: how do I get the value of the clicked row and column?
The code I have is this:
JS:
$.ajax({
type: 'POST',
url: url,
data: json,
success: function(data) {
var response_array = JSON.parse(data);
var columns = ['id', 'name', 'email', 'telephone', 'website', 'city'];
var table_html = ' <tr>\n' +
'<th id="id">Id</th>\n' +
'<th id="name">Bedrijfnaam</th>\n' +
'<th id="email">E-mail</th>\n' +
'<th id="telephone">Telefoon</th>\n' +
'<th id="website">Website</th>\n' +
'<th id="city">Plaats</th>\n' +
'</tr>';
for (var i = 0; i < response_array.length; i++) {
//create html table row
table_html += '<tr>';
for (var j = 0; j < columns.length; j++) {
//create html table cell, add class to cells to identify columns
table_html += '<td class="' + columns[j] + '" >' + response_array[i][columns[j]] + '</td>'
}
table_html += '</tr>'
};
$("#posts").append(table_html);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
Here is the HTML:
<div class="tabel">
<table id="posts">
</table>
</div>
I have tried the following:
$('#posts').click(function(){
console.log("clicked");
var id = $("tr").find(".id").html();
console.log(id);
});
Sadly this will only give me the id of the first row, no matter where I click.
Any help is appreciated!
Ramon
The below approach should be able to find the ID
$('#post').on('click', function(e){
var id = $(e.target).closest('tr').find(".id").html();
console.log(id)
})
HTML content of clicked row
$('#posts tr').click(function(){
$(this).html();
});
text from clicked td
$('#posts tr td').click(function(){
$(this).text();
});
If you are using ajax and you are redrawing elements, you will not catch em via click function. You will need to add on function:
$(document).on('click','#posts tr td','function(){
$(this).text();
});
You may try to use AddEventListener for your table, it will work for sure.
Like this:
let posts = document.getlementById('posts');
posts.addEventListener('click',(e) => {
// anything you need here, for example:
console.log(e.target);
e.preventDefault();
});
As well - it will be fine not to use same IDs for elements in a grid (like id="id" which you have), it should be different.

How to generate Dynamic button in a table row and open new page on button click

i actually having a requirement of generating dynamic table from services url and after that generating dynamic table.This is i worked it out but what i want is
How to generate a dynamic button on each table row with click event.
After generating the button how we can assign click events to the button i mean suppose in a table there are four columns like date,id number,name,location and on the clicking on the each column or related to that cell it has to redirect to a new page.
or
if a table row is clicked and there are 4 columns are there like date,id number,name,location the click event has will take date as a parameter and click event function and then it have to proceed to the next page/redirect
$('#btn_Day').click(function () {
var ex = document.getElementById("dpp_info");
var clOptions = ex.options[ex.selectedIndex].value;
var clOptions1 = ex.options[ex.selectedIndex].text;
var dt = todaydate;
var dt1 = todaydate;
$.ajax({
type: 'GET',
url: xxxxx.xxxxx.xxxxx,
data: frmDate_=" + dt + "&toDate_=" + dt1 + "",
success: function (resp) {
var Location = resp;
var tr;
for (var i = 0; i < Location.length; i++) {
tr = tr + "<tr>";
tr = tr + "<td style='height:20px' align='left'>" + Location[i].Name + "</td>";
tr = tr + "<td style='height:20px' align='left'>" + Location[i].Date + "</td>";
tr = tr + "<td style='height:20px' align='left'>" + Location[i].IdNum + "</td>";
tr = tr + "</tr>";
};
document.getElementById('Wise').innerHTML = "<table class='r'>" + "<tr><thead ><th style='height:20px'>Location</th>"
+ "<th style='height:20px'>Date</th>" + "<th style='height:20px'>Id Num</th>" + "</tr></thead>"
+ tr +
"<tr></tr>" +
"</table>";
document.getElementById('Wise').childNodes[0].nodeValue = null;
},
error: function (e) {
window.plugins.toast.showLongBottom("Please Enable your Internet connection");
}
});
});
now in the image if u see there are four columns suppose if i click on the idnumb and there records related to that particular number has to be displayed in separate page
Looking For Help!
After some more discussion on this the key was to just use the handler and pass any values using attributes. You can see the fiddle here
https://jsfiddle.net/p2fpbkuo/3/
$('.button-click').off();
$('.button-click').on('click', function () {
// navigate to new page
// console.log('button click')
// what you could do here is get the serialnumber which is an attribute on the button
var id = $(this).attr('data-id') // as long as this is unique this should always work
var filteredResults = results.filter(function (result) {
if (result.SerialNumber.toString() === id.toString()) {
return result;
}
});
var selectedRowValues = filteredResults[0];
// this will contain all the values for that row
console.log(selectedRowValues)
// var dataValue = $(this).attr('data-url'); // dont't need this any more
window.open(selectedRowValues.Url)
});

Select All checkbox only selects checkboxes that are currently in the page [not in other page indices]

I have a jquery dynatable. Here is the screenshot of my current table
My problem is that when I clicked the select all checkbox, the only checkboxes that are in the first page of the table are selected (in each row) but the others remain unselected. Here is my code so far:
// I have omitted the table head part for the sake of simplicity
/********************************
TABLE BODY
********************************/
var tableRows = "";
//iterate each result object
for (var row in result.results.bindings) {
tableRows += "<tr>";
//iterate each value
for (var key in result.results.bindings[row]) {
if (result.results.bindings[row].hasOwnProperty(key) && (resultSetVariables.length==0 || _.contains(resultSetVariables, "?" + key))) {
var value = "x";
if( result.results.bindings[row][key].value != undefined ) {
val = result.results.bindings[row][key].value;
if(val.match(regexURL)) {
value = '' + val.substr(val.lastIndexOf('/') + 1) + '';
}
else
value = val;
}
tableRows += "<td>" + value + "</td>";
}
}
tableRows+='<td><input type="checkbox" class="singleSelect"> </td>';
tableRows += "</tr>";
// console.log(tableRows);
};
$("#results_container").children().detach();
//create unique id
var id = Math.floor( Math.random()*99999 );
//append a new table to the DOM
$("#results_container").append('<table id="result_table' + id + '" cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered"><thead><tr></tr></thead><tbody></tbody></table>');
$("#results_container").append('<input type="button" class="btn" id="calculate_similarity" value="calculate_similarity" style="float:right;"/>');
$("#results_container").append("<label style='float:right;'><input class='mahoutSelection' id='selectAll' type='checkbox' value='selectAll' style='float:right;'>selectAll</label>");
//append head and body to tabley
$('#results_container table thead tr').append(tableHead);
$('#results_container table tbody').append(tableRows);
$('#results_container table tbody').append(tableRows);
//add the results table
this.resultTable = $('#results_container table').dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>"
, "sPaginationType": "bootstrap"
, "oLanguage": {
"sLengthMenu": "_MENU_ records per page"
}
});
$('input[id="selectAll"]').on('click', function(){
if ( $(this).is(':checked') ) {
$("input[class=singleSelect]").each(function () {
$(this).prop("checked", true);
});
}
else {
$("input[class=singleSelect]").each(function () {
$(this).prop("checked", false);
});
}
});
So how could I fix it so that, when I click the select all, it checks all checkboxes ?

Creating html table using Javascript not working

Basically, I want the user the just change the 'height' variable to how ever many rows he wants, and then store the words which each td in the row should contain, and the code should then generate the table.
My html is just this:
<table id="newTable">
</table>
This is my Javascript:
<script type="text/javascript">
var height = 2; // user in this case would want 3 rows (height + 1)
var rowNumber = 0;
var height0 = ['HeadingOne', 'HeadingTwo']; // the words in each td in the first row
var height1 = ['firstTd of row', 'secondTd of row']; // the words in each td in the second row
var height2 = ['firstTd of other row', 'secondTd of other row']; // the words in each td in the third row
$(document).ready( function() {
createTr();
});
function createTr () {
for (var h=0; h<height + 1; h++) { // loop through 3 times, in this case (which h<3)
var theTr = "<tr id='rowNumber" + rowNumber + "'>"; // <tr id='rowNumber0'>
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
for (var i=0; i<window['height' + rowNumber].length; i++) {
if (i == window['height' + rowNumber].length-1) { // if i==2, then that means it is the last td in the tr, so have a </tr> at the end of it
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td></tr>";
$('#rowNumber' + rowNumber).append(theTr); // append to the end of the Tr
} else {
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td>";
$('#rowNumber' + rowNumber).append(theTr);
}
}
rowNumber += 1;
}
}
</script>
I did 'alert(theTr);' and 'alert(theTd);' and they looked correct. How come this code doesn't generate any table?
You should change the line
$('#rowNumber' + rowNumber).append(theTr);
into
$('#rowNumber' + rowNumber).append(theTd);
You are adding the Tr-Code again in the inner loop, but you actually wanted to add the Td-Code.
All that window["height"+rowNumber] stuff is a poor way to do it. Use an array, and pass it as a parameter to the function so you don't use global variables. And use jQuery DOM creation functions instead of appending strings.
<script type="text/javascript">
var heights = [['HeadingOne', 'HeadingTwo'], // the words in each td in the first row
['firstTd of row', 'secondTd of row'], // the words in each td in the second row
['firstTd of other row', 'secondTd of other row'] // the words in each td in the third row
];
$(document).ready( function() {
createTr(heights);
});
function createTr (heights) {
for (var h=0; h<heights.length; h++) { // loop through 3 times, in this case (which h<3)
var theTr = $("<tr>", { id: "rowNumber" + h});
for (var i=0; i<heights[h].length; i++) {
theTr.append($("<td>", { "class": "row"+h + " column"+i,
text: heights[h][i]
}));
}
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
}
}
</script>
JSFIDDLE

Categories

Resources