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

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();
}

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);
})
})

How to copy the value from one input box to another input box?

By clicking on Add New Row button, new input boxes can be generated. I want to copy the value from one input box (First column - Hours ) to another input box (Second Column - In Office).
Screenshot:
First Row: Value is copied from one input box to another input box when it is a static element. Here input box is created by HTML.
Dynamic Rows: Value is not copied from one input box to another input box when it is a dynamic element. Here input box is created by JavaScript.
Issue:
Value is not copied because the elements are generated dynamically with same id and name
What I tried:
$(document).ready(function() {
$('[data-toggle="tooltip"]').tooltip();
var actions = $("table td:last-child").html();
// Append table with add row form on add new button click
$(".add_new").click(function() {
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="number" name="hours[]" id="hours"></td>' +
'<td><input type="number" name="inoffice[]" id="inoffice"></td>' +
'</tr>';
$("table").append(row);
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function() {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function() {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function() {
$(this).parent("td").html($(this).val());
});
}
});
});
function sync() {
var hours = document.getElementById('hours');
var inoffice = document.getElementById('inoffice');
inoffice.value = hours.value;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th>Hours</th>
<th>In Office</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" name="hours[]" id="hours" onkeyup="sync()" onClick="sync()"></td>
<td><input type="number" name="inoffice[]" id="inoffice"></td>
</tr>
</tbody>
</table>
<input type="button" id="add_new" name="add_new" class="add_new" value="Add New Row">
You should not be duplicating id attributes as it's invalid HTML and will lead to other issues. Use class attributes instead to group elements by common behaviour patterns.
From there you can use a delegated event handler to handle all the .hours elements that will ever exist in the DOM.
Also note that inline event attributes are outdated and should be avoided where possible.
$('table').on('input', '.hours', function() {
$(this).closest('tr').find('.inoffice').val(this.value);
});
$(document).ready(function() {
$('[data-toggle="tooltip"]').tooltip();
var actions = $("table td:last-child").html();
$(".add_new").click(function() {
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="number" name="hours[]" class="hours"></td>' +
'<td><input type="number" name="inoffice[]" class="inoffice"></td>' +
'</tr>';
$("table").append(row);
$('[data-toggle="tooltip"]').tooltip();
});
$(document).on("click", ".add", function() {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function() {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function() {
$(this).parent("td").html($(this).val());
});
}
});
$('table').on('input', '.hours', function() {
$(this).closest('tr').find('.inoffice').val(this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th>Hours</th>
<th>In Office</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" name="hours[]" class="hours"></td>
<td><input type="number" name="inoffice[]" class="inoffice"></td>
</tr>
</tbody>
</table>
<input type="button" id="add_new" name="add_new" class="add_new" value="Add New Row">
Start by creating an MCVE. That means remove all the code that isn't part of the problem. This will make everything clearer.
Remove IDs, since IDs must be unique, we better use classes instead.
$(document).ready(function() {
$(".add_new").click(function() {
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="number" name="hours[]" class="hours"></td>' +
'<td><input type="number" name="inoffice[]" class="inoffice"></td>' +
'</tr>';
$("table").append(row);
$('[data-toggle="tooltip"]').tooltip();
});
});
$(document).on("keyup", ".hours", function(){
$(this).parent().parent().find(".inoffice").val(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th>Hours</th>
<th>In Office</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" name="hours[]" class="hours"></td>
<td><input type="number" name="inoffice[]" class="inoffice"></td>
</tr>
</tbody>
</table>
<input type="button" id="add_new" name="add_new" class="add_new" value="Add New Row">

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>

Jquery Datatables add new row in json table

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.

Retrieve first column value of checkbox selected row of an HTML table and modify the DB accordingly

So here is the table below
I wanted to store the (#) of every checkbox selected row in an array variable preferably which I can later use them to modify the database, viz: change a certain DB field where the id is: 37, 39, 42, 46, etc.
A similar question here, which provides a much more broader solution
The code which selects the row after checkbox:selected
<script>
$(document).ready(function() {
$('#example').DataTable();
$('td :checkbox').bind('change click', function () {
$(this).closest('tr').toggleClass('highlight', this.checked);
}).change();
} );
</script>
<style type="text/css">
.highlight td{
background-color: #a2c4ab;
}
</style>
Any reference or guidance would help
You can use this to get rows where a checkbox is selected:
var selector = '#myTable tr input:checked';
$.each($(selector), function(idx, val) {
// iterate here
});
And then for each row you can get values with e.g.:
var id = $(this).parent().siblings(":first").text();
var update = $(this).parent().siblings(":first").next().text();
Meaning get my parent and get the first sibling, or next to first sibling etc. You can adjust that for your table.
Putting it altogether below - note posting to your DB totally depends on information not in your question so you can just do an AJAX post or something.
$('#test').on('click', function() {
var updates = [];
var selector = '#myTable tr input:checked';
$.each($(selector), function(idx, val) {
var id = $(this).parent().siblings(":first").text();
var update = $(this).parent().siblings(":first").next().text();
updates.push({id: id, update: update});
});
// test values
console.log(JSON.stringify(updates));
// post to DB - fill in your details
//$.ajax({
// url: 'your_script.php',
// type: 'post',
// data: updates,
// success: function() {
// alert('done');
// }
//});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>Id</th>
<th>DB update</th>
<th>Checker</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Hughie</td>
<td><input type="checkbox" id="foo1" /><label for="foo1">Foo1</label></td>
</tr>
<tr>
<td>2</td>
<td>Dewey</td>
<td><input type="checkbox" id="foo2" /><label for="foo2">Foo2</label></td>
</tr>
<tr>
<td>3</td>
<td>Louis</td>
<td><input type="checkbox" id="foo3" /><label for="foo3">Foo3</label></td>
</tr>
<tr>
<td>4</td>
<td>Chewey</td>
<td><input type="checkbox" id="foo4" /><label for="foo4">Foo4</label></td>
</tr>
</tbody>
</table>
<button id="test">Get checked IDs</button>

Categories

Resources