i am trying to add / remove rows dynamically in / from a table using JQuery and the DataTables plugin, at a specific index.
$('#jt').dataTable();
The rows i try to add is some additional info, which i get by clicking on a row (ajax). Each row has a unique id that i pass as an argument.
$('#jt').on('click','.togetinfo',function() {....
$.get(functions, { id: id }).done(function(data) {
....
For each result i add the content to a var and add it after the row i want.
$.each(jsonresult, function(i,item){
subentries = subentries + ....... /* the info */
});
$('#jt > tbody > tr').eq(id).after(subentries);
This works perfectly on the first page, but on the second page of the entries (paging) it does not insert the new data.
The fnAddData() of the "DataTables" API inserts the data on the end of the entire table.
Does anyone has an idea of how to make it work on all the pages?
The false was found in the indexes of each row after the first page.
Each index (on click) must be recalculated.
var rowIndex = oTable.fnGetPosition( $(this).closest('tr')[0] );
rowIndex = rowIndex - oSettings._iDisplayStart;
Related
I am using jquery plugin DataTables for building nice table
var table = $('#example').DataTable({
"data": source
});
I would like that make an each for all rows in table
Unfortunately this way may be out of date and does't work with new version (it launchs an error)
$(table.fnGetNodes()).each(function () {
});
And this way only works only for visibles rows (10 first rows because other rows are paginated)
table.each( function ( value, index ) {
console.log( 'Data in index: '+index+' is: '+value );
} );
Do you known how to loop to all rows please?
I finally found:
var data = table.rows().data();
data.each(function (value, index) {
console.log(`For index ${index}, data value is ${value}`);
});
Datatables have an iterator for each row rows().every() with this referring to the context of the current row being iterated.
tableName.rows().every(function(){
console.log(this.data());
});
If you are using the legacy DataTables then you can get all the rows even the paginated ones, as shown below...
table.fnGetNodes(); // table is the datatables object.
So we can loop through the rows by using .each() method provided by jQuery.
jQuery(table.fnGetNodes()).each(function () {
// You can use `jQuery(this).` to access each row, and process it further.
});
for example, this data has three fields UserID, UserName and isActive and we want to show only active users
The following code will return all the rows.
var data = $('#myDataTable').DataTable().rows().data();
We will print only active users
data.each(function (value, index) {
if (value.isActive)
{
console.log(value.UserID);
console.log(value.UserName);
}
});
I have two different IDs. One auto increment (using jquery) from an ID called id="H+currentRow+"(+currentRow+ is the current row). And another that does an ajax request to PHP that appends the form with an id="Z#"(# will be depending on the ID in the database).
Ive done this:
$(document).ready(function(){
$("input").change(function(){
var sum=0;
$("[id^=H]").each(function(){
sum=sum+(+parseInt(this.value));
});
var sum2=0;
$("[id^=Z]").each(function(){
sum2=sum2+(+parseInt(this.value));
});
var total = sum + sum2;
if(isNaN(total)) {
var total = 0;
}
$("#total").text(total);
});
});
But thats not working. It works for the first fields but it work for anything else thats being appended. Anyone know whats going on and why its not working?
when you bind an event direct to an element, new elements appended to page will not trigger the event. you have to bind a parent element where inputs are appended to.
Try this bind:
$('body').on('change', 'input', function () {
// your code remain the same here...
});
you can be more specifc than body, binding the event to parent elements of input.
I am building scheduling software. I am using a number of tables to display times/dates, etc.
In one particular table there are cells with id's that list the date and employee id number.
I am trying to setup a trading shift system. When the cell is click an ajax function is performed.
Here is an example cell:
<td id="tblcell-2013_03_13-id_3" class="displayShift">$data placed here</td>
Jquery code:
$(document).ready(function () {
// I can't do this because each id is different
$("td#tblcell").click(function () {
alert('it works!');
});
// I can't do this because there other other td elements on the same page in other tables
$("td").click(function () {
alert('it works!');
});
});
How do I set up a function that is activated when a specific cell is clicked that also passess var data to the function in a script that has other td table elements that can't be referenced in this function?
thanks
You can use the td[id^="tblcell"] selector to select all TDs with their ID starting with tblcell
$('td[id^="tblcell"]').click(function() {
// ... do stuff ...
});
Demo for attribute-value-starts-with selector: http://jsfiddle.net/ARkxD/
ok, so I have a database comprising of two tables, products and suppliers.
All suppliers fill in a form and their data is then stored in the suppliers table, and the products table contains a list of all of the products, so when the supplier fills in the form, he can choose as many products as he wishes as I use jQuery JSON and AJAX to get the list of all of the products and then populate a drop down list with all of them in it, which can then be cloned as many times as is needed.
The problem I am sitting with now is, how do I insert all of the different products the supplier chooses into the supplier table, or should I rather just relate all of the products he chooses to the one supplier for better normalization since all the products are already there?
I will be using jQuery $.ajax to POST the form data in JSON format to a waiting PHP file, which will then parse it and insert the data into the database.
So basically, I need to figure out how to relate the data in the database to achieve the best normalization possible, and I need to figure out a way of inserting a variable amount of products into the suppliers table or find a way to relate the many products he chooses to the one supplier.
I am very new to relational databases, so any advice on how to proceed would be a great help, so would any other advice you guys may have!
The jQuery code I use to populate clone and POST the products the supplier chooses:
$(document).ready(function() {
var count = 0;
//when clicked it will remove the closest div with a class of 'container'
$("span.remove").live('click', function(){
$(this).closest("div.container").fadeOut(400, function(){
$(this).remove();
$('#button').attr('disabled','');
});
});
//initialize the button
$('#button').attr('disabled','');
$('#button').click(function(){
var count = $("#systems_wrapper > .container").size();
var lastID = $("#systems_wrapper > .container:last").attr('id');
var exploded = lastID.split("_");
var increment = Number(exploded[1])+1;
//if the user has selected 5 products, disable the 'add' button
if(count >= 5){
$('#button').attr('disabled','disabled');
}else {
$('#button').attr('disabled','');
}
//clone the first drop down and give it a different ID, as well as it's child elements
var test = $('#systems_0.container').clone().attr('id', 'system_' + increment).appendTo('#systems_wrapper');
test.children(':nth-child(2)').append('<span class="remove"></span>');
test.children(':nth-child(2)').children(':first').attr('id', 'mail_' + increment).attr('class','dropDowns').attr('onchange','test();');
});
//get the products JSON object returned from test_post.php and run the necessary functions on the returned data
$.getJSON("test_post.php", function(data){
//clean out the select list
$('#box').html('');
//run the loop to populate the drop down list
$.each(data, function(i, products) {
$('#box').append(
$('<option></option>').html(products.products)
);
});
});
});
//this gets all of the products chosen and then gets each ones value and ID, and then posts it to the qwer.php file
function test(){
var sections = $('#systems_wrapper').find('.dropDowns');
var newArray = new Array();
sections.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
var o = { 'id': id, 'value': val };
newArray.push(o);
});
alert(newArray);
$.ajax({
type: "POST",
url: "qwer.php",
dataType: 'json',
data: { json: JSON.stringify(newArray) }
});
}
Thanx in advance!
If i understand the problem correctly from a database level, should you be using an intermediate table called something like ProductSupplier containing a Product_ID and Supplier_ID column.
Then when a supplier selects a product, add both the supplier and product id to a new column in this table.
This will allow multiple suppliers to pick the same product and multiple products to be picked by the same supplier.
EDIT: I meant to say "add both the supplier and product id to a new ROW in this table"
Im using the following jQuery, which sets the id of the last item in a UL to 'last_item'.
function oldest() {
j('ul li:last-child').addClass( 'last_item' );
oldestName = j('.last_item').attr('id');
alert('last ID is:'+ oldestName +'.');
}
j(window).scroll(function(){
if (j(window).scrollTop() == j(document).height() - j(window).height()){
j.ajax({
url: "older.php?oldest="+oldestName+"",
cache: false,
success: function(html){
j(".older").html(html);
oldest();
}
})
}
});
oldest(); //Call function on page load
$('.button2').click(function() {
j('.older ul > *').clone().hide().appendTo('.tweets ul').slideDown();
oldest();
});
While scrolling older.php is called which contains:
$oldest = $_GET['oldest'];
$getolder = mysql_query(" SELECT * FROM table where date < $oldest ORDER BY date DESC LIMIT 20");
However what currently happens is the records from the database do get pulled back, stored in a hidden DIV. I then use the jQuery to add these records to the end of the list.
However the next time i scroll to the bottom of the page and press the button, the same records are added to the lists.
Can any help me to find out why this is?
Essentially it seems $oldest isnt being updated with the new last UL item date.
You'll need to remove the original "last_item" class from list item before you add it to the new last item...
j('ul li').removeClass( 'last_item' );