Jquery Datatables add new row in json table - javascript

I am using: jquery.dataTables.js from: https://datatables.net
I amtrying to add a new row in my json table.
I could not get it work any ideas why not?
jsfiddle: http://jsfiddle.net/f7debwj2/17/
html:
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>order</th>
<th>name</th>
<th>country</th>
</tr>
</thead>
</table>
<button id="addRow">Add New Row</button>
<table id="newRow">
<tbody>
<tr>
<td>Line 2
<input type="hidden" value="2" /> </td>
<td>DVap
<input type="hidden" value="DVap" /> </td>
<td>
<input type="text" value="22" /> </td>
</tr>
</tbody>
</table>
jquery:
$(document).ready(function() {
var dt = $('#example').dataTable();
dt.fnDestroy();
});
$(document).ready(function() {
var url = 'http://www.json-generator.com/api/json/get/clmDuyndua?indent=2';
var table = $('#example').DataTable({
ajax: url,
rowReorder: {
dataSrc: 'order',
},
columns: [{
data: 'order'
}, {
data: 'name'
}, {
data: 'place'
}]
});
// add row
$('#addRow').click(function() {
//t.row.add( [1,2,3] ).draw();
var rowHtml = $("#newRow").find("tr")[0].outerHTML
console.log(rowHtml);
dt.row.add($(rowHtml)).draw();
});
});

Like you can see in the documentation you need to change this line:
dt.row.add($(rowHtml)).draw();
to:
table.row.add($(rowHtml)).draw();
The updated fiddle.

Your actual error was
Uncaught ReferenceError: dt is not defined
Just change table.row.add($(rowHtml)).draw() instead of dt.row.add($(rowHtml)).draw() inside button click event.

Related

How can i get multiple radio button value from table in jquery into another table

I want to make checkbox and get the selected table row into another table on click
This is the table to click the the checkbox:
<table class="table table-bordered maintable">
<tbody>
<tr class="text-center">
<td>Pilih</td>
<td>Nama Obat</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>lalal</td>
</tr>
</tbody>
</table>
<input type="button" value="transfer" class="transterrows">
This is the main table, table to show selected row that have been checklist:
<table class="table table-bordered secondtable">
<tbody>
<tr>
<td>Nama Obat</td>
</tr>
</tbody>
</table>
This is the jquery that I tried but failed:
$(function () {
$(document).on("click", "transterrows", function () {
var getselectedvalue = $(".maintable input:checked").parents("tr").clone().appendTo($(".secondtable tbody").add(getselectedvalue));
})
})
$(function () {
$(document).on("click", ".transterrows", function () {
var getselectedvalue = $(".maintable input:checked").parents("tr").clone().appendTo($(".secondtable tbody").add(getselectedvalue));
})
})
It seems to work if you add the '.' in you click function to select the class transterrows.
Try this code
$(function () {
$(".transterrows").on("click", function () {
var getselectedvalue = $(".maintable input:checked").parents("tr").clone();
$(".secondtable tbody").append(getselectedvalue);
})
})

Jquery DataTables Live DOM Ordering on Checkbox column not working

I have a DataTable in my .NET Core application which has a checkbox column. I would like to be able to sort/order the table by checkbox value using the arrow buttons in the table header. In order to achieve this I have used the code from the DataTables Live DOM Ordering example here: https://datatables.net/examples/plug-ins/dom_sort.html
However, the column re-ordering does not work. If I inspect the elements I can see that there is something happening to the elements as they flash, however the order of the rows is not changing.
Here is the HTML:
<table id="airportsTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>IsoCode</th>
<th>Name</th>
<th>TimezoneName</th>
<th>TimezoneStandardName</th>
<th>
Required
<input type="checkbox" id="selectAllCheckbox" value="false" />
</th>
</tr>
</thead>
<tbody>
#{ foreach (var airport in airportList) //Index , update after iteration, so that non-model data can be attached
{
string iso = airportList[tableIndex].IsoCode;
<tr>
<td>
<label id="isoCode">#airportList[tableIndex].IsoCode</label>
</td>
<td>
<label id="name">#airportList[tableIndex].Name</label>
</td>
<td>
<label id="timeZoneName">#airportList[tableIndex].TimeZoneName</label>
</td>
<td>
<label id ="timeZoneStandardName">#airportList[tableIndex].TimeZoneStandardName</label>
</td>
<td>
<input type="checkbox" asp-for="#airportList[tableIndex].Required" id="requiredCheckbox" onclick="requiredChanged(this, '#airportList[tableIndex].IsoCode' )" />
</td>
</tr>
tableIndex++;
}
}
</tbody>
</table>
And here is the JQuery:
$.fn.dataTable.ext.order['dom-checkbox'] = function ( settings, col )
{
return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
return $('input', td).prop('checked') ? '1' : '0';
} );
}
$(document).ready(function () {
var airportsTable = $('#airportsTable').DataTable({
"pageLength": 50,
"columns": [
null,
null,
null,
null,
{ "orderDataType": "dom-checkbox" }
]
});
Any help would be greatly appreciated, TIA!
Add this to your table after your columns section:
"columnDefs": [
{ "orderDataType": "dom-checkbox", targets: 5 }
]
https://datatables.net/reference/option/columns.orderDataType

save dynamic table into json

what is the best way to save a dynamic table data in to json.
I have two tables that i want to save in to one json file.
i"m able to console the regular table data but i"m unable to locate the td value of a dynamic table.
my plan to save to json and clear the forum for additional DC/pop info adding
so please check the save button and help me understand how to continue
1. save the popisp table
2. clear and make it ready for the next pop entry.
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js">
$(document).ready(function(){
$(".add-row").click(function(){
var name = $("#ispname").val();
var capasity = $("#ispcapasity").val();
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + capasity + "</td></tr>";
$('#popisp tr:last').after(markup);
});
$(".delete-row").click(function(){
$('#popisp').find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
$(".save_asJSON").click(function(){
var pop_name = document.getElementById("popname").value
jsonobj.pops[pop_name] = {
name: document.getElementById("popname").value,
city: document.getElementById("popcity").value,
subnet: document.getElementById("popsubnet").value,
}
console.log(jsonobj);
});
});
var jsonobj = {
pops: {}
};
</script>
<body>
<table id="PoP_Details">
<tr>
<td>Pop name:</td>
<th colspan="2"><input id="popname" name='pops[name]'></input></th>
</tr>
<tr>
<td>City:</td>
<th colspan="2"><input id="popcity" name='pops[name][city]'></input></th>
<tr>
<td>POP Subnet</td>
<th colspan="2"><input id="popsubnet" name='pops[name][subnet]'></input></th>
</tr>
</table>
<form>
<input type="text" id="ispname" placeholder="Name">
<input type="text" id="ispcapasity" placeholder="capasity">
<input type="button" class="add-row" value="Add ISP">
</form>
<div class="wrap">
<table id="popisp">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>capasity</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
</div>
<button type="button" class="delete-row">Delete Row</button>
<button type="button" class="save_asJSON">Save</button>
</body>
here is how I like my json to looks like
{
"pops": {
"pop1": {
"name": "pop1",
"city": "blabla",
"subnet": "192.168.1.0/24",
"isps": [
{
"name": "isp1",
"capasity": "10M"
},
{
"name": "isp2",
"capasity": "10M"
}
]
},
"pop2": {
"name": "pop2",
"city": "blabla",
"subnet": "192.168.2.0/24",
"isps": [
{
"name": "isp3",
"capasity": "20M"
},
{
"name": "isp4",
"capasity": "30M"
},
{
"name": "isp5",
"capasity": 500M"
}
]
}
}
}
I can suggest the following guidance :
Save inputs as jQuery variables for further use, not necessary but usefull, ex :
var $input = $('#popname');
Add a function that use the table, iterate through the <tr> in <tbody> and retrieve the <td> to compose object to save for each row, return it as an array.
Add a function that use the inputs to clear the form
Call the two function above when saving the array, the first to add the data to the json saved, the second to clear the form.
I show bellow an update of your snippet with complete modification, but I suggest you use use the guidance to implement it in a way that suits your needs.
$(document).ready(function(){
// Inputs as jQuery variables
var $nameInput = $("#popname");
var $cityInput = $("#popcity");
var $subnetInput = $("#popsubnet");
var $ispNameInput = $("#ispname");
var $ispCapacityInput = $("#ispcapasity");
var $popispTable = $('#popisp');
// array for convenience loop
var inputs = [$nameInput, $cityInput, $subnetInput,
$ispNameInput, $ispCapacityInput];
// function to clear all inputs and remove isp rows
function clearForm() {
inputs.forEach(e => e.val(''));
$popispTable.find('tbody').find('tr').remove();
$popispTable.find('tbody').append($('<tr>'));
}
// function that return an array of isp rows data
function ispTableData() {
var rows = $popispTable.find('tbody').find('tr');
if (!rows.length) return [];
console.log(rows.length);
var data = rows.toArray().reduce((data, e, k) => {
var tds = $(e).find('td');
if (!tds.length) return [];
data.push({
checked: $(tds[0]).find('input').is(":checked"),
name: $(tds[1]).text(),
capasity: $(tds[2]).text()
});
return data;
}, []);
return data;
}
$(".add-row").click(function(){
var name = $("#ispname").val();
var capasity = $("#ispcapasity").val();
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + capasity + "</td></tr>";
$('#popisp tr:last').after(markup);
// eventually clear row form inputs here as well
});
$(".delete-row").click(function(){
$('#popisp').find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
$(".save_asJSON").click(function(){
var pop_name = document.getElementById("popname").value
jsonobj.pops[pop_name] = {
name: $("#popname").val(),
city: $("#popname").val(),
subnet: $("#popsubnet").val(),
// add the isp rows data
isps: ispTableData()
}
console.log(jsonobj);
// clear the form
clearForm();
});
});
var jsonobj = {
pops: {}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table id="PoP_Details">
<tr>
<td>Pop name:</td>
<th colspan="2"><input id="popname" name='pops[name]'></input></th>
</tr>
<tr>
<td>City:</td>
<th colspan="2"><input id="popcity" name='pops[name][city]'></input></th>
<tr>
<td>POP Subnet</td>
<th colspan="2"><input id="popsubnet" name='pops[name][subnet]'></input></th>
</tr>
</table>
<form>
<input type="text" id="ispname" placeholder="Name">
<input type="text" id="ispcapasity" placeholder="capasity">
<input type="button" class="add-row" value="Add ISP">
</form>
<div class="wrap">
<table id="popisp">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>capasity</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
</div>
<button type="button" class="delete-row">Delete Row</button>
<button type="button" class="save_asJSON">Save</button>
</body>

DataTables rows under deleted row gets undefined after a row is deleted

I have a datatable. There is a Delete button on every row. As soon as I delete a row using .remove() function the respective row gets deleted, but afterwards on clicking the Save button, the rows below the deleted rows gets undefined.
Here is the sample code:
HTML
<body>
<form method="POST"></form>
<div class="container">
<table cellpadding="0" cellspacing="0" border="0" class="dataTable" id="example">
<thead>
<tr>
<th>Name</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type ="text" id="name_0" value ="hello0"/></td>
<td><button id="btn_0" onclick="del(this);">Delete</button></td>
</tr>
<tr>
<td><input type ="text" id="name_1" value ="hello1"/></td>
<td><button id="btn_1" onclick="del(this);">Delete</button></td>
</tr>
<tr>
<td><input type ="text" id="name_2" value ="hello2"/></td>
<td><button id="btn_2" onclick="del(this);">Delete</button></td>
</tr>
<tr>
<td><input type ="text" id="name_3" value ="hello3"/></td>
<td><button id="btn_3" onclick="del(this);">Delete</button></td>
</tr>
</tbody>
</table>
<input type="button" value="Save" id="btnSave"/>
</div>
</body>
JS:
$(document).ready(function() {
var i =0;
$('#example').dataTable({
"aoColumns": [
null, { "bSortable": false }
],
"aaSorting": [],
"pageLength": 10,
"lengthMenu": [5, 10, 25, 50, 100, 200]
});
$('#btnSave').click(function(){
var tbl = $('#example').dataTable();
$(tbl.fnGetNodes()).each(function () {
alert($(this).find("#name_" + i).val());
i++;
});
});
});
function del(element)
{
var btnId = element.id;
var idIndex = btnId.substring(btnId.indexOf("_") + 1);
var table = $('#example').DataTable();
table.row($($("#btn_" + idIndex)).parents('tr')).remove().draw();
}
Here is a non-working Demo for the same.
How can I delete a row and then clicking on the Save button, the rows below the deleted row should not get undefined.
Any assistance would be appreciated.
This happens because there is a mismatch between row index and ID of the INPUT element after you delete the row.
Short workaround would be to use the following code instead:
alert($(this).find("input[type=text]").val());
See updated jsFiddle for code and demonstration.
$(document).ready(function () {
$('#btnSave').click(function () {
$('#example tbody tr').each(function () {
alert($(this).find("td:eq(0)").find('input').val());
});
});
});
function del(element) {
$(element).closest('tr').remove();
}

Tablesorter with ajax refresh not working with more than one

I'm using jQueryUI tabs that has a table on each page. The tables are sorted by Tablesorter 2.0.
The following code works great when I have a single table undergoing a refresh on a page. If I add a second table w/ a refresh, only the first one updates. Can someone tell me how I can get two tables to be sorted by tablesorter with ajax refreshes of the data?
The reload is run through this JS function:
$(function () {
$(".tsRefresh").tablesorter({
headers: {
'.cbsort': { sorter: 'checkbox' },
'.nosort': { sorter: false, parser: false }
},
theme : 'jui',
headerTemplate : '{content} {icon}',
widgets : ['saveSort', 'uitheme'],
widgetOptions : {
zebra : ["odd", "even"]
}
});
function getBjson() {
var Tid = $('.tsRefresh').data('id');
var Ttable = $('.tsRefresh').data('table');
var Tbody = $('.tsRefresh').find('tbody').attr('id')
$.ajax({
type: "POST",
url: "ajax.php",
data: 'table=' + Ttable +'&id=' + Tid,
success: function(output) {
document.getElementById(Tbody).innerHTML = output;
// update tablesorter cache
$(".tsRefresh").trigger("update");
},
error: function (xhr, ajaxOptions, thrownError) {
$('#messageResponse').fadeIn(500);
$('#messageResponse').addClass('ui-state-error ui-corner-all').removeClass('ui-highlight-error');
$('#messageResponse').text(xhr.status + ' ' + thrownError + ': Something went wrong - check your inputs and try again.');
}
});
}
if( $('.tsRefresh').length) {
var Ttime = $('.tsRefresh').data('time');
var timer = setInterval(getBjson, Ttime);
getBjson();
}
});
The following is the table code:
<div id="tabs-1">
<fieldset>
<table width="100%" id="issue" name="issue" class="tsRefresh" data-id="<?=$item_id?>" data-table="eq-load" data-time="10000">
<thead>
<tr class="bold">
<th class="cbsort"><input type="checkbox" class="checkall"> </th>
<th>OAN/ID</th>
<th>Category</th>
<th>Desc</th>
<th>Issued To</th>
<th>SN</th>
</tr>
</thead>
<tbody id="container1">
</tbody>
</table>
</fieldset>
</div>
<div id="tabs-2">
<fieldset>
<table width="100%" id="my-load" name="my-load" class="tsRefresh" data-id="<?=$item_id?>" data-table="eq-load-me" data-time="10000">
<thead>
<tr class="bold">
<th class="cbsort"><input type="checkbox" class="checkall"> </th>
<th>OAN/ID</th>
<th>Category</th>
<th>Desc</th>
<th>Issued To</th>
<th>SN</th>
</tr>
</thead>
<tbody id="container2">
</tbody>
</table>
</fieldset>
</div>
My PHP script (ajax.php) outputs the following to the tablesorter's table:
<tr class="dialog-hover" data-table="eq-load-item" data-id="<?=$item_id?>">
<td align="center"><input type="checkbox" id="row-<?=$item_id?>" value="<?=$item_id?>"></td>
<td align="center" valign="top"><?=$item_oan?>-<?=$item_id?></td>
<td><?=$item_cat?></td>
<td align="center" valign="top"><?=$item_desc?></td>
<td align="center" valign="top"><?=$issue_name?></td>
<td align="center" valign="top"><?=$item_serial?></td>
</tr>

Categories

Resources