I've already initialized dataTable once when i do DataTable().row.add(), but i still need to do some extra methods with that datatable. For example, i need to do this api method:
$('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'colvis' ] } );
but there is an alert DataTables warning: table id=dataTable - Cannot reinitialise DataTable for every rows i have in my datatables, it means if i have 10 rows, this alert will show 10 times, althought after i skip all these alert, everything looks fine then, and there is no error in the console,too
Here is my code:
following some comments below, i've UPDATED my code
var myTable = $('#dataTable').DataTable({ dom: 'Bfrtip', buttons: ['colvis'] });
var row = $('#dataTable tbody tr:first');
myTable.row.add([
'<img width="70px" height="100px" src="' + childData.poster + '">',
'<p style="height:100px;overflow:auto;text-align:center">' + childData.title + '</p>',
'<a style="text-align:center" href="javascript: void(0)" onclick="showModalListChapter(' + "'" + childKey + "'" + "," + "'" + childData.title + "'" + ')">' + totalChapters + '</a>',
'<p style="height:100px;overflow:auto;text-align:center">' + childData.author + '</p>',
'<p style="width:100px;height:100px;overflow:auto;text-align:center">' + childData.category + '</p>',
'<p style="text-align:center">' + childData.state + '</p>',
'<p style="width:350px;height:100px;overflow:auto;text-align:center">' + childData.description + '</p>',
'<p style="text-align:center">' + childData.totalViews + '</p>',
'<p style="text-align:center">' + childData.totalLikes + '</p>',
'<button class="btn btn-danger" style="margin-bottom:20px" onclick="deleteManga(' + "'" + childKey + "'" + ')">xóa</button>' +
'<button class="btn btn-warning" onclick="showModalUpdateManga(' + "'" + childKey + "'" + ')">sửa</button>',
'<p style="text-align:center">' + childData.createdDate + '</p>',
'<p style="text-align:center">' + childData.updatedDate + '</p>',
]).draw(false);
The same problem still happens
Most likely (hard to say for 100% because you haven't given us your code segment), you need to init the datatable to a variable, and then use the object in that variable to add your rows. So:
$(document).ready(function() {
var myTable = $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'colvis' ] } );
//and then, under some condition, and likely inside a function:
myTable.row.add(data);
} );
The DataTables documentation on row.add() has further examples.
UPDATE
Here is a Fiddle demo that shows the basics for initializing a Datatable and then adding a row: https://jsfiddle.net/zephyr_hex/enkmhb2t/13/
Related
I'm trying to retrieve multiple data from my remote php file and display them dynamically, i usually do this with jquery when i'm coding cordova. i'm using nativescript now.
This is the jquery code i use before
$.getJSON(serviceURL + 'getroutes.php?station='+station, function(data) {
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li>'+
'<img src="js/citybus.png" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + '</p>' +
'<p class="line2">' + difference + ' Out' + '</p>' +
'<p class="line3" style="color:'+ color +';margin-left:60px">' + SeatsLeft + ' seats left </p>' +
'<button style="display:'+ display +'" class="bubble" data-difference="' + hoursMin + '" data-route="' + employee.firstName + '" data-busnum="' + employee.lastName + '" onclick="bookSeat(this);">' + '<center><img src="js/seat.jpg" style="height:15px;width:15px;"/></center>' + '</button>'
+ '<button data-id="' + employee.id + '" data-diff="' + hoursMin + '" data-name="' + employee.firstName + '" class="bubble" style="margin-right:30px" onclick="setReminder(this);">' + '<center><img src="js/bell.png" style="height:15px;width:15px;"/></center>' + '</button></li>');
if(index && index % 4 === 0) {
$('#employeeList').append('<center><div class="adSpace2" style="margin-top:2.5px;margin-bottom:2.5px;">'+'</div></center>');
}
});
setTimeout(function(){
scroll.refresh();
});
});
Please how do i do this with nativescript?
You'll want to use the Fetch API.
const Observable = require('tns-core-modules/data/observable').Observable
const model = new Observable()
function loaded(args) {
args.object.bindingContext = model
fetch(serviceURL + 'getroutes.php?station='+station).then(res => model.set('employees', res.items))
}
exports.loaded = loaded
And then in your View XML:
<Page xmlns="http://www.nativescript.org/tns.xsd" xmlns:lv="nativescript-ui-listview" aloaded="loaded">
<StackLayout>
<ListView items="{{employees}}">
<Label class="line1" text="{{firstName}}" />
</ListView>
</StackLayout>
</Page>
I parsed JSON objects and made a table structure to display the elements. I wanted to make rows of table editable. This is is the code i used to form the table.
(jsonDatag.data).forEach(function(item) {
var _tr = '<tr class="' + item.symbol + '"><td>' + item.symbol + '</td><td class="' + hclass + '">' + item.highPrice + '</td><td class="' + lclass + '">' + item.lowPrice + '</td><td class="' + oclass + '">' + item.openPrice + '</td><td class="' + ltclass + '">' + item.ltp + '</td><td>' + item.previousPrice + '</td><td>' + item.lastCorpAnnouncementDate + '</td></tr>'
_tbody += _tr
});
_thead = _thead + _tbody;
$('.mytable').html(_thead)
}
Now I added these lines to make my rows editable but it is not reflecting in my output.
$('tr.'+item.symbol+'').each(function() {
$(this).html('<input type="text" value="' + $(this).html() + '" />');
});
What is going wrong here and how can i correct it ?
Editable rows is not working in table
This seems to be confusing since it is the td which is editable.
Also this snippet
$('tr.' + item.symbol + '').each(function() {
$(this).html('<input type="text" value="' + $(this).html() + '" />');
});
probably will place an input.
If you are looking to make a editable td then
<td contenteditable="true">
will work
I have an ajax script that retrieves more X results from the database. The number of results depend on the offset hidden field value. The script doubles it. After these X new data, it should append after it another block of an image, but I noticed that if I print in the console the selected element, it shows this:
[prevObject: m.fn.init[1], context: document, selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"]context: documentlength: 0prevObject: m.fn.init[1]selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"proto: Object[0]
[prevObject: m.fn.init[1], context: document, selector: "#revendas_conteudo .load_more .item_estoque:nth-child(6)"]context: documentlength: 0prevObject: m.fn.init[1]selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"proto: Object[0]
Which means it's trying to append to something that still doesn't exist. Below is the Ajax script:
function appendAd(offset, no) {
console.log($('#revendas_conteudo .load_more .item_estoque:nth-child(' + offset + ')'));
$('#revendas_conteudo .load_more .item_estoque:nth-child(' + offset + ')').after(
'<div style="float: left; margin-top: 8px; margin-bottom: 8px; width: 100%; text-align: center;" class="anuncio">' +
'<img src="/uploads/publicidades/publicidade_busca_' + no + '.jpg">' +
'</div>'
);
}
$('#revendas_conteudo .btn_carregar_mais').on('click', function (e) {
$.ajax({
url: '/auto/carros/load_more',
data: {
'offset': $('#offset').val(),
'limit': $('#limit').val(),
'no': $('#no').val()
},
success: function (data) {
obj = JSON.parse(data);
i = 0;
max = obj.total === obj.offset;
var newOffset;
no = parseInt($('#no').val()) + 1;
$('#limit').val(obj.limit);
$('#offset').val(obj.offset);
$('#no').val(obj.no);
$.each(obj.res, function (k, v) {
newOffset = parseInt($('#offset').val()) + 1;
$('#revendas_conteudo .load_more').append(
'<div class="item_estoque">' +
'<div class="avatar">' +
'<img src="/uploads/carros/destaque/' + obj.res[i].imagem_destaque + '"/>' +
'</div>' +
'<div class="texto_anuncio">' +
'<h4>' + obj.res[i].modelo.substring(0, 19) + '</h4>' +
'<div class="detalhes">' +
'<span>' + obj.res[i].marca + ' | ' + obj.res[i].combustivel + ' | ' + obj.res[i].cor + '</span>' +
'<span>' + obj.res[i].ano + '</span>' +
'<span>' + obj.res[i].kilometragem + ' km</span>' +
'</div>' +
'<span class="anunciante">' + obj.res[i].nome_anunciante + '</span>' +
'</div>' +
'<div class="texto_anuncio_right">' +
'<span class="preco"> R$ ' + obj.res[i].preco + '</span>' +
'Veja Mais' +
'</div>' +
'</div>'
);
i++;
$('#offset').val(newOffset);
$('#no').val(no);
if (newOffset == obj.total) {
$('#revendas_conteudo .btn_carregar_mais').css({backgroundColor: '#999'}).html('Sem mais resultados').attr('disabled', true);
}
});
},
complete: function() {
appendAd($('#offset').val(), no);
}
});
});
How can I do it? To append a block after another HTML block has been appended?
I have a param called "exraData" which can be a string or array (depends on some conditions).
I have to display some content using java script.
in case "exraData" is a String the content is displayed well by the following code:
this.resulto = '<div class="avatarHeight">' +
'<div class="avatar">' + spanPic + '</div>' +
'<div class="info ' + company + '">' + item.show +
'<div class="tt-hint">' + exraData + '</div>' +
'</div>' +
'</div>';
In case it is array I use the following code but nothing is displayed:
this.resulto = '<div class="avatarHeight">' +
'<div class="avatar">' + spanPic + '</div>' +
'<div class="info ' + company + '">' + item.show
for(var i=0;i<exraData.length;i++){
+'<div class="tt-hint">' + exraData[i] + '</div>'
}
+'</div>' +
'</div>';
You can't have a for loop inline. Here is the for loop outside with the desired result.
var spanPic='tempPic';
var company='xyz';
var item={};
item.show='temp';
var exraData=['one','two','three'];
this.resulto = '<div class="avatarHeight">' +
'<div class="avatar">' + spanPic + '</div>' +
'<div class="info ' + company + '">' + item.show;
for(i=0;i<exraData.length;i++){
this.resulto +='<div class="tt-hint">' + exraData[i] + '</div>';
}
this.resulto+='</div>' + '</div>';
document.write(this.resulto);
I am building a table row in a jQuery $.ajax() call that builds a row on successful execution of a PHP script.
I'm calling a function that builds a new table row based on the script results. Here is the function:
function addNewRow(addDocs, newClassID, classNumberAdd, classNameAdd) {
var newRow = '';
newRow += $('#classesTable tbody:last').after('<tbody>' +
'<tr bgcolor="#EFE5D3" style="font-weight: bold;">' +
'<td width="35px"><a class="classEditLink" name="' + newClassID + '" href="#">Edit</a></td>' +
'<td width="20px"><input type="checkbox" class="chkSelectToDelete" name="deleteClasses[]" value="' + newClassID + '" /></td>' +
'<td>' + classNumberAdd + '</td>' +
'<td>' + classNameAdd + '</td>' +
'</tr>');
if (addDocs == 'true') {
$('#docsTable input[type="checkbox"]:checked').each(function() {
var $row = $(this).parents('tr');
var docID = $row.find('td:eq(0) input').val();
var docName = $row.find('td:eq(1)').html();
var docDescription = $row.find('td:eq(2)').text();
newRow += $('#classesTable tbody:last').append('<tr class="classDocsRow">' +
'<td></td>' +
'<td align="right"><input type="checkbox" class="chkRemoveDocs" name="removeDocs[]" value="' + docID + '-' newClassID + '" /></td>' +
'<td width="245px">' + docName + '</td>' +
'<td width="600px">' + docDescription + '</td>' +
'</tr>');
});
//$('#classesTable tbody:last').append('<tr class="classDocsRow"><td></td><td align="right"><input type="checkbox" class="chkRemoveDocs" name="removeDocs[]" value="' + docID + '-' newClassID + '" /></td><td width="245px">' + docName + '</td><td width="600px">' + docDescription + '</td></tr>');
} else {
newRow += $('#classesTable tbody:last').append('<tr class="classDocsRow">' +
'<td colspan="4">' +
'<strong>No documents are currently associated with this class.</strong>' +
'</td>' +
'</tr>');
}
return newRow;
}
Aptana Eclipse IDE is reporting an error in two places in the "if (addDocs == 'true')" section: The first error, "missing ) after argument list", is on the second line after "newRow += ..." and the second error "missing ; before statement" is two lines after that. Note that I also have that entire section in one line (not broken up with string concats) commented out shortly after that. That shows only one error, the error about missing a right paren.
If I comment out everything in the if clause and pass addDocs as false, the else clause returns a new row as expected.
This must be simply a js syntactic problem, but I can't see what I'm doing wrong.
Any help will be greatly appreciated!
You are missing the + here:
' + docID + '-' + newClassID + '" /></td>' +
^
The second error is probably just a result of the first error.