How to edit table html? - javascript

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

Related

is there a way to get the value from the first cell in html table row using javascript only?

I'm trying to figure out how to get the value from the first column of selected row inside the HTML table
i'm selecting the row using button created using this js code :
let tr = document.querySelectorAll("table tbody tr");
Array.from(tr).forEach(function (trArray) {
let button = document.createElement("i");
let td = document.createElement("td");
button.innerText = "";
button.className = "fa fa-eye";
button.style.color = "black";
button.hidden = "hidden";
button.onmouseover = "this.style.cursor='pointer'";
button.onclick = "viewrow(this)";
button.setAttribute("onclick", "viewrow(this)");
td.append(button);
trArray.append(td);
});
the table is created from code behind using stringbuilder
what I tried is this:
StringBuilder sb = new StringBuilder();
sb.Append("<table id=" + "contractstable" + " runat=" + "server" + " " + "class=" + "table" + " >");
sb.Append("<caption>البنود</caption>");
sb.Append("<thead>");
sb.Append("<tr>");
sb.Append("<th>رقم البند</th>");
sb.Append("<th>رقم الفاتورة</th>");
sb.Append("<th>صنف البند</th>");
sb.Append("<th>سعر القطعة</th>");
sb.Append("<th>القيمة</th>");
sb.Append("<th>الخصم</th>");
sb.Append("<th>المجموع</th>");
sb.Append("<th>حذف</th>");
sb.Append("</tr>");
sb.Append("</thead>");
sb.Append("<tbody id=" + "mytbody" + ">");
foreach (DataRow dr in dt.Rows)
{
sb.Append("<tr><td data-label=" + "رقم-البند" + ">" + dr["contract_id"]
+ "</td><td data-label= " + "رقم-الفاتورة" + " > " + dr["bill_id"]
+ "</td><td data-label=" + "صنف-البند" + ">" + dr["contract_category"]
+ "</td><td data-label=" + "سعر-القطعة" + ">" + dr["item_price"]
+ "</td><td data-label=" + "القيمة" + ">" + dr["amount"]
+ "</td><td data-label=" + "الخصم" + ">" + dr["discount"]
+ "</td><td data-label=" + "المجموع" + ">" + dr["total"] + "</td></tr>");
}
sb.Append("</tbody>");
sb.Append("</table>");
ltrTable.Text = sb.ToString();
then i want to get the selected row id , what i have tried :
function deleterow(element) {
var mytbody = document.getElementById("mytbody");
var firstchild = mytbody.querySelector("td");
var allName = firstchild.innerText;
var hiddentext2 = document.getElementById("myrow_id");
hiddentext2.focus();
hiddentext2.value = allName;
hiddentext2.blur();
}
You can use querySelector to get the first element. If it has more than one of similar elements, it always gets the first one.
Your cell does not have value either. You should use innerText instead.
function getrowid(element) {
var mytbody = document.getElementById("mytbody");
var firstchild = mytbody.querySelector("td");
var allName = firstchild.innerText;
console.log(allName)
}
getrowid()
<table>
<tbody id="mytbody">
<tr>
<td>First</td>
<td>Second</td>
</tr>
<tr>
<td>Third</td>
<td>Fourth</td>
</tr>
</tbody>
</table>
const tbody = document.querySelector("#myTbale > tbody");
const tds = tbody.querySelectorAll("td");
let tdVal = [];
tds.forEach(td => {
tdVal.push(td.innerText);
})
console.dir(tdVal[0]);
<table border="1" id="myTbale">
<thead>
<th>header 1</th>
<th>header 2</th>
</thead>
<tbody>
<tr>
<td>1st cell</td>
<td>1st cell</td>
</tr>
</tbody>
</table>

Copying Checked rows from one table to another table

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

How to add class to appending td elements

I am trying to make a blinking color on a table row with jquery
(function blink() {
$('.colorredd').fadeOut(500).fadeIn(500, blink);
})();
here the html part.
<table id="userdata3" border="2">
<thead>
<th>Afdeling</th>
<th>Åben</th>
</thead>
<tbody class="colorredd"></tbody>
</table>
here the way how I append the items:
$(obj).each(function () {
var tbl3Row = "<tr " + (parseInt(obj.Total) > 3 ? " class='colorred'" : "") + (parseInt(obj.Total) < 4 ? " class='colorred'" : "") + ">" + "<td>" + obj.Title + "</td>" + "<td>" + obj.Total + "</td>" + "</tr>"
table3Rows += tbl3Row;
});
}
It blinks both rows on table.
What I am trying to do is blink only the second row.
I am guessing that i need to add class to beyond Total td and just remove the class from html tbody.
But I dont know how I can add class to that td specifically.
var tbl3Row = "<tr " + (parseInt(obj.Total) > 3 ? " class='colorred'" : "") + (parseInt(obj.Total) < 4 ? " class='colorred'" : "") + ">" + "<td>" + obj.Title + "</td>" + "**<td>**" + obj.Total + "</td>" + "</tr>"
and her the my css:
.colorred td:nth-child(2){
background-color:red;
}
It blinks both rows because you are binding fadeIn/Out to colorredd class. which is on every row.
Add another class, maybe lastRow to only the last table row. And bind blink to it.
(function blink() {
$('.lastRow').fadeOut(500).fadeIn(500, blink);
})();

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>

Categories