Copying Checked rows from one table to another table - javascript

Actually i am looking to copy the checked rows from the table of one div (table 1) to table of another div(table 2). But with the below script, when i check more than one checkbox, the first checked row is replaced by the lastly checked row. But i want like each checked row of table 1 should come in table 2 as one by one.
Any help appreciated. Thanks in advance!!!
HTML
<div class="form-group" id="jqcc" >
<table id="order-table" name="order-table">
<tr>
<th>Select</th>
<th>Medication</th>
<th>Max Issue Limit</th>
</tr>
<tbody></tbody>
</table>
</div>
Javascript
<script>
var tableControl = document.getElementById('order-table');
$('#jqcc').click(function () {
var result = []
var x1;
var tab;
var count = document.querySelectorAll('input[type="checkbox"]:checked').length;
$('input:checkbox:checked', tableControl).each(function () {
result.push($(this).parent().next().text() + "," + "<br>"); // refers title of product
$(this).closest('tr').find('input').each(function () {
x1 = $(this).val(); // refers price of product
})
tab = "<tr><td>" + result + "</td>";
tab += "<td>" + x1 + "</td>";
tab += "<td>" + x1 + " </td>";
tab += "<td><button type='button' onclick='deletePerson(this);' class='btn btn-default'> <span class='glyphicon glyphicon-remove' /></button></td>";
tab += "</tr>";
tab += "</tbody>"
$("#charges").html("<table id='peopleTable' class='table table-bordered table-condensed table-striped'><thead><tr><th>Description</th><th>Actual Amount</th> <th>Claim Amount</th> <th></th></tr></thead>" + tab + "</table>").show();
});
});
</script>

You try to change:
<script>
var tableControl = document.getElementById('order-table');
$('#jqcc').click(function () {
var result = []
var x1;
var tab = "";
var count = document.querySelectorAll('input[type="checkbox"]:checked').length;
$("#charges").html("<table id='peopleTable' class='table table-bordered table-condensed table-striped'><thead><tr><th>Description</th><th>Actual Amount</th><th>Claim Amount</th> <th></th></tr></thead><tbody></tbody></table>").show();
$('input:checkbox:checked', tableControl).each(function () {
result.push($(this).parent().next().text() + "," + "<br>"); // refers title of product
$(this).closest('tr').find('input').each(function () {
x1 = $(this).val(); // refers price of product
//
tab = "<tr><td>" + result + "</td>";
tab += "<td>" + x1 + "</td>";
tab += "<td>" + x1 + " </td>";
tab += "<td><button type='button' onclick='deletePerson(this);' class='btn btn-default'> <span class='glyphicon glyphicon-remove' /></button></td>";
tab += "</tr>";
// append row html to table with id
$("#peopleTable").append(tab);
})
});
});

Related

Not getting onclick event to fire from programmatically built table

I have a table that is programmatically added with an onclick event that calls a specific javascript function with the id of the row I want to edit. However it is not called. I have tried changing the button by adding a class and trying to get something there but it does not work. This used to work and I cannot figure out why or how to fix it.
function buildTable() {
$.ajax({
url: "getTable.php",
dataType: "json",
success: function(result) {
if (result != null) {
$('#measurements tbody tr').remove();
result.forEach(function (measurement) {
var message = "<tr><td>" + dateFromtimestamp(measurement.weigh_date) + "</td>";;
message += "<td>" + measurement.weight + "</td>";
message += "<td><input type='hidden' value='" + measurement.id + "'>" + measurement.waist + "</td>";
message += "<td>" + measurement.upperBp + "</td>";
message += "<td>" + measurement.lowerBp + "</td>";
message += "<td>" + measurement.comment + "</td>";
message += "<td><button type='button' class='btn btn-outline-warning' onlick='editRow(" + measurement.id + ")'>";
message += "<span class='glyphicon glyphicon-pencil'></span></button> ";
message += "<button type='button' class='btn btn-outline-danger' onlick='removeRow(" + measurement.id + ")'>";
message += "<span class='glyphicon glyphicon-remove'></span></button></td></tr>";
$('#measurements').append(message);
});
}
}
});
}
The following is the HTML table it is being added to:
<div class="panel panel-info">
<div class="panel-heading text-center">Past measurements</div>
<div class="panel-body">
<table class="table table-striped" id="measurements">
<thead class="thead-dark">
<th scope="col">Date</th>
<th scope="col">Weight</th>
<th scope="col">Waist</th>
<th scope="col">Systolic (Upper)</th>
<th scope="col">Diastolic (Lower)</th>
<th scope="col">Comment</th>
<th scope="col">Action</th>
</thead>
<tbody>
</tbody>
</table>
<div class="row"> </div>
</div>
</div>
This is the edit function in question just in case I miss something with the argument signature:
function editRow(id) {
$.ajax({
url: "getMeasurement.php",
type: "post",
dataType: "json",
data: {
"id": id
},
success: function(data) {
if (data != null) {
data.forEach(function(result){
var id = result.id;
$('#editMeasurement').modal('show');
$('#editupper').val(result.upperBp);
$('#editlower').val(result.lowerBp);
$('#editwaist').val(result.waist);
$('#editweight').val(result.weight);
$('#editcomment').text(result.comment);
$('#editRowHidden').val(id);
});
}
}
});
}
I have tried changing the button by adding a class:
and trying to catch the event with $('.editRow').on("click", function() {} event with the same results.
You have a typo onlick instead of onclick.
Also, you could consider to use passive event listener as:
$(document).on("click", <target>,<your function>});
where <target> is the jquery selector for you button
and <your function> your callback.
This would increase readability and as well helps to keep the separation between HTML and JS. And also work for dynamically inserted targets.
Thanks to kmgt. If it was a snake it would have bit me. Have to use 'onclick' instead of 'onlick'.
First of all I agree with #dmitrii-g that you should use event-delegation to be able to handle any events on elements, that were added after DOM was rendered. (added dynamically). After that you should try to debug/print to console any information needed to ensure that you are passing correct values into your function. I've prepared sample example which will demonstrate this approach:
const result = [{
weigh_date: '01/01/2019',
weight: '200lbs',
id: 1,
waist: 'waist',
upperBp: 'upperBp',
lowerBp: 'lowerBp',
comment: 'comment'
},
{
weigh_date: '01/01/2015',
weight: '100lbs',
id: 2,
waist: 'waist',
upperBp: 'upperBp',
lowerBp: 'lowerBp',
comment: 'comment'
}
];
function buildTable() {
if (result != null) {
$('#measurements tbody tr').remove();
result.forEach(function(measurement) {
var message = "<tr><td>" + measurement.weigh_date + "</td>";
message += "<td>" + measurement.weight + "</td>";
message += "<td><input type='hidden' value='" + measurement.id + "'>" + measurement.waist + "</td>";
message += "<td>" + measurement.upperBp + "</td>";
message += "<td>" + measurement.lowerBp + "</td>";
message += "<td>" + measurement.comment + "</td>";
message += "<td><button type='button' class='btn btn-edit btn-outline-warning' id='" + measurement.id + "'>Edit</button> ";
message += "<button type='button' class='btn btn-delete btn-outline-danger' id='" + measurement.id + "'>Remove</button></td></tr>";
$('#measurements').append(message);
});
}
}
$('#measurements').on('click', '.btn-edit', function() {
const id = $(this).attr('id');
console.log('ID to be edited: ' + id);
// your stuff here
});
$('#measurements').on('click', '.btn-delete', function() {
const id = $(this).attr('id');
console.log('ID to be deleted: ' + id);
// your stuff here
});
buildTable();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-info">
<div class="panel-heading text-center">Past measurements</div>
<div class="panel-body">
<table class="table table-striped" id="measurements">
<thead class="thead-dark">
<th scope="col">Date</th>
<th scope="col">Weight</th>
<th scope="col">Waist</th>
<th scope="col">Systolic (Upper)</th>
<th scope="col">Diastolic (Lower)</th>
<th scope="col">Comment</th>
<th scope="col">Action</th>
</thead>
<tbody>
</tbody>
</table>
<div class="row"> </div>
</div>
</div>
try this
$(document).on("click","tr",function() {
console.log(this,"click");
});

Get table row value with jQuery/JS

I am trying to get table value names with the following code:
my table :
function CreateBlockDeployTableRow(data) {
return "<tr>" +
"<td>" + data.EnvTypeName + "</td>" +
"<td>" + data.AppTypeName + "</td>" +
"<td>" + deleteBtn + "</td>" +
"</tr>";
}
my button:
var deleteBtn = '<button class="btn btn-danger unblock-button btn-sm
glyphicon glyphicon-minus" type=button > </button> '
on click function:
function UnblockRequestHandler()
{
$('.unblock-button').click(function () {
sendUnblockDeploySubmitHandler();
});
}
and here I want to send my Environment and Application to server side and take the value of the rows in the table , but the code is not working and not taking anything:
function sendUnblockDeploySubmitHandler() {
var $row = jQuery(this).closest('tr');
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function (i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML +
'<br/>';
alert(values);
});
console.log(values);
}
html code :
<div class="tbl-responsive">
<table id="blockDeployTable" class="table table-hover
requestsblockDeployTable" style="font-size: 0.8em; margin-top: 120px;
text-align:center">
<thead>
<tr>
<th>Environment</th>
<th>Repo</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Where am I wrong here I cannot understand?
You could just pass the click event through to the sendUnblockDeploySubmitHandler function:
$('.unblock-button').click(function () {
sendUnblockDeploySubmitHandler(event); // pass event to function
});
function sendUnblockDeploySubmitHandler(event) {
var $row = $(event.target).closest('tr'); // event.target is the button
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function (i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
console.log(values);
}
I've put together a jsbin to show this working: https://jsbin.com/sosimudubi/1/edit?html,js,console,output
You are trying to access jQuery(this) in the sendUnblockDeploySubmitHandler() method but the this handle does not refer to the button element. I would suggest you to directly pass the callback function when you bind the click event.
function UnblockRequestHandler() {
$('.unblock-button').click(sendUnblockDeploySubmitHandler);
}
This way, you can access the corresponding button element using jQuery(this) in the sendUnblockDeploySubmitHandler()

splice in javascript change values of my other objects

NOTE! this is for an extra credit assignment, so I am not looking for code re-write but rather guidance in what I am doing wrong. I have gone through my code several times and I feel like I am just missing something very minor. I have completed it fully with the exception of the following error:
I created an array of objects.
Everything starts off fine. I can create objects and they are added to the array and successfully displayed on my screen with correct values.
The trouble arises when I delete an object from the array. It does delete this object and removes it from my displayed list, but suddenly all the remaining objects get new values. These new values match those of the LAST object I added to the array. I need them to retain their original values!
var tableContent = document.getElementById("tableContent");
var tableString = " ";
var counter = 0;
var courseArray = [];
tableContent.innerHTML = tableString;
function Course(number, title, hours, prereq) {
this.number = number;
this.title = title;
this.hours = hours;
this.prereq = prereq;
}
function createCourse() {
var number = document.getElementById("number-field");
var title = document.getElementById("title-field");
var hours = document.getElementById("hours-field");
var prereq = document.getElementById("prereq-field");
courseArray.push(new Course(number, title, hours, prereq));
buildCourseTableBody();
}
function buildCourseTableBody() {
tableString += "<tr>" +
"<td>" + counter + "</td>" +
"<td>" + courseArray[counter].number.value + "</td>" +
"<td>" + courseArray[counter].title.value + "</td>" +
"<td>" + courseArray[counter].hours.value + "</td>" +
"<td>" + courseArray[counter].prereq.value + "</td>" +
"<td><button id='delete' onClick='deleteCourse(" + counter + ")'><img id=counter src='../image/delete.png' alt='delete course'></button></td>" +
"</tr>";
counter++;
tableContent.innerHTML = tableString;
}
function deleteCourse(counterIndex) {
courseArray.splice(counterIndex, 1);
counter--;
tableString = "";
for (var i = 0; i < courseArray.length; i++) {
tableString += "<tr>" +
"<td>" + i + "</td>" +
"<td>" + courseArray[i].number.value + "</td>" +
"<td>" + courseArray[i].title.value + "</td>" +
"<td>" + courseArray[i].hours.value + "</td>" +
"<td>" + courseArray[i].prereq.value + "</td>" +
"<td><button id='delete' onClick='deleteCourse(" + i + ")'><img id=counter src='../image/delete.png' alt='delete course'></button></td>" +
"</tr>";
}
and HTML code(everything in main, which is wrapped in body. js file is included):
<main id="main-index">
<h1 id="page-caption">CS Department Course Catalog</h1>
<div id="course-list">
<p id="course-list-caption">Course List</p>
<table>
<thead>
<tr>
<th>Count</th>
<th>Number</th>
<th>Title</th>
<th>Hours</th>
<th>Prereq</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tableContent">
</tbody>
</table>
</div>
<div id="course-edit">
<p><input id="number-field" placeholder="Course #, e.g. CS234"></p>
<p><input id="title-field" placeholder="Course title, e.g. Database and Wed Systems Development"></p>
<p><input id="hours-field" placeholder="Credit hours, e.g. 3.0"></p>
<p><input id="prereq-field" placeholder="Course prereqs, e.g. CS150, CS111"></p>
<p><button id="add" onClick="createCourse()">+</button></p>
</div>
</main>
Your error is in createCourse. You are assigning the HTML-Elements instead of their value.
function createCourse() {
var number = document.getElementById("number-field").value;
var title = document.getElementById("title-field").value;
var hours = document.getElementById("hours-field").value;
var prereq = document.getElementById("prereq-field").value;
courseArray.push(new Course(number, title, hours, prereq));
buildCourseTableBody();
}
The class course will hold a reference to the element itself. Like that your functions which generate the table itself, will always get the most current value of the input boxes.
Notice:
Don't forget to adapt buildCourseTableBody and deleteCourse.

Append button to a table row dynamically using jquery

I have an array of JavaScript JSON objects which is being parsed from a JSON formatted-string. Now what I'm doing is that I'm looping through the array and append the data to a table within the page.
jQuery Code:
$.each(objArr, function(key, value) {
var tr = $("<tr />");
$.each(value, function(k, v) {
tr.append($("<td />", {
html: v
}));
$("#dataTable").append(tr);
})
})
The code works perfectly and the table is getting populated successfully
But what I'm looking for is that, I want to add a delete button at the end of the row, by which the user will delete the row, and it also important to handle the click event in order to perform the required action
I've done this in another way, but it is not that efficient, I want to use the code above to accomplish that as it is more efficient:
for (var i = 0; i < objArr.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + objArr[i]["empID"] + "</td>";
var td2 = "<td>" + objArr[i]["fname"] + "</td>";
var td3 = "<td>" + objArr[i]["lname"] + "</td>";
var td4 = "<td>" + objArr[i]["phone"] + "</td>";
var td5 = "<td>" + objArr[i]["address"] + "</td>";
var td6 = "<td >" + objArr[i]["deptID"] + "</td>";
var td7 = "<td>" + objArr[i]["email"] + "</td>";
var td8 = "<td>" + '<button id="' + objArr[i]["empID"] + '" value="' + objArr[
i]["empID"] + '" onclick="onClickDelete(' + objArr[i]["empID"] +
')">Delete</button>' + "</td></tr>";
$("#dataTable").append(tr + td1 + td2 + td3 + td4 + td5 + td6 + td7 + td8);
}
Any suggestions please?
Try something like this:
$.each(objArr, function (key, value) {
var tr = $("<tr />");
$.each(value, function (k, v) {
tr.append($("<td />", { html: v }));
tr.append("<button class='remove' />");
$("#dataTable").append(tr);
})
})
This shall append the button at the end of the tr with class remove.
Try this, I've include event handler for the each buttons inside the table.
CHANGES:
Adding Event Listener for each buttons inside the table.
Call method (function) with parameters.
Note:
I am using, fadeOut method for fading purposes only. So you can see the changes. You can change the script as your need.
EXPLAINS :
var cRow = $(this).parents('tr'); on this line we have $(this) which mean we've select the button object that you've clicked, and search the parent with tag-name tr. We need to do this because we need to take control of all data inside the tr object.
var cId = $('td:nth-child(2)', cRow).text(); has mean search second td object wich located on cRow object. And take the text from the selected td.
JQUERY REFFERENCES :
.parents()
:nth-child()
$(this) OR $(this)
$(document).ready(function() {
var jsonData = [
{id: 'A01', name: 'Fadhly'},
{id: 'A02', name: 'Permata'},
{id: 'A03', name: 'Haura'},
{id: 'A04', name: 'Aira'}
];
$.each(jsonData, function(key, val) {
var tr = '<tr>';
tr += '<td>' + (key + 1) + '</td>';
tr += '<td>' + val.id + '</td>';
tr += '<td>' + val.name + '</td>';
tr += '<td><button class="delete" data-key="'+ (key + 1) +'">Delete</button></td>';
tr += '</tr>';
$('tbody').append(tr);
});
$('button.delete').on('click', function() {
var cRow = $(this).parents('tr');
var cId = $('td:nth-child(2)', cRow).text();
var intKey = $(this).data('key');
cRow.fadeOut('slow', function() {
doDelete(cId, intKey);
});
});
function doDelete(param1, param2) {
alert('Data with\n\nID: [' + param1 + ']\nKey: [' + param2 + ']\n\nRemoved.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="100%">
<thead>
<tr>
<th>#</th>
<th>Id</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

How to edit table html?

I am building a page with a table, with the ability to add, edit, and delete. I have the add and delete functionality working but not the edit or save. Can anyone tell what is wrong with these functions?
Whenever I click on the edit button it will delete the row (Select check box it will either delete or edit).
Here is my code:
<table id="packageTable">
<thead>
<tr>
<th>Select</th>
<th>Make</th>
<th>Model</th>
<th>SKU#</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
rowNew = 1;
removeRow = -1;
function tableColumn(){
row = rowNew;
if (removeRow >0){
editList();
}else{
var make = $("#make").val();
var modal = $("#model").val();
var sNumber = $("#sNumber").val();
var mPrice = $("#mPrice").val();
var newCol = "<tr id = 'newCol" + row +"'>" +
"<td><input type = 'checkbox'>"+ "</td>" +
"<td id\"mChoice" + row + "\">"+ make + "</td>" +
"<td id\"m0Choice" + row + "\">" + modal +"</td>" +
"<td id\"skChoice" + row +"\">" + sNumber +"</td>"+
"<td id\"prChoice" + row +"\">" + mPrice +"</td>" +
"<td><button onclick ='eRow(" + row + ")'>Edit</button>" +
"<td><button onclick ='delete(" + row + ")'>Delete</button>" +
"</tr>";
$("#packageTable").append(newCol);
rowNew++;
$("#make").val("");
$("#model").val("");
$("#sNumber").val("");
$("#mPrice").val("");
}
}
function eRow(row) {
$("#make").val($('#mChoice'+row).html());
$("#model").val($('#m0Choice'+row).html());
$("#sNumber").val($('#skChoice'+row).html());
$("#mPrice").val($('#prChoice'+row).html());
remove = row;
}
function editsSave(){
$('"#mChoice' + removeRow).html($('#make').val());
$('"#m0Choice' + removeRow).html($('#model').val());
$('"#sNumber1' + removeRow).html($('#sNumber').val());
$('"#mPrice' + removeRow).html($('#mPrice').val());
remove = -1;
}

Categories