guys i jnow it is dummy question but i spent hours in this and cant reach .. i want to add row to an existing table and this row consists of checkbox and 4 textboxes .. when i run it the textboxes appears but the checkbox dont .. here is my code
function addRow() {
var i = 1;
var table = document.getElementById("table");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var html = [];
html.push("<table id='table'>\n<body>");
html.push("<tr><td><input type='checkbox' name='chk'/></td>");
var cell = row.insertCell(html);
for ( var propertyNames in grid.data[0]) {
cell = row.insertCell(i);
var element = document.createElement("input");
element.type = "text";
element.size = 10;
element.name = "input"+i;
cell.appendChild(element);
html.push("<td>" + cell + "</td>");
i++;
}
html.push("</tr>");
html.push("</body>\n</table>");
}
The problem is you are creating a array with the markup for the checkbox, but it is never added to the table
function addRow() {
var i = 1;
var table = document.getElementById("table");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell = row.insertCell();
var element = document.createElement("input");
element.type = "checkbox";
element.name = "chk";
cell.appendChild(element);
for (var propertyNames in grid.data[0]) {
cell = row.insertCell(i);
element = document.createElement("input");
element.type = "text";
element.size = 10;
element.name = "input" + i;
cell.appendChild(element);
i++;
}
}
var grid = {
data: [{
x: 1,
y: 1
}]
};
addRow();
<table id="table"></table>
Related
I am facing a problem for this day I am creating a pop-up cart with a table, I create an array with
ID | NAME | QUANTITY | PRICE
then I generate the table from this array with javascript.My problem is I want to be able to update the price and the total when I change the quantity for a specific item line (= quantity in the table row). This should work for all generated table rows.
This is my javascript code:
var cartCount = 0;
var Total = 0;
var id = 1;
var labels = ['Name', 'Quantity', 'Price'];
var items;
var cartElement = document.getElementById('cartDisplay');
var counterElement = document.getElementById('counterDisplay');
function cartClick(name, quantity, price) {
const x = {
id: id,
name: name,
quantity: quantity,
price: price
};
if (Obj.some(e => e.name === x.name)) {
console.log('already there');
} else {
Obj.push(x);
cartCount = cartCount + 1;
Total = Total + x.price;
id = id +1;
buildTable(labels, Obj, document.getElementById('modalBODY'));
items = Obj;
console.log(items);
}
CheckCart(cartCount);
console.log(cartCount);
}
function CheckCart(counter) {
if (counter > 0) {
cartElement.style.display = "block";
counterElement.innerHTML = counter;
} else {
cartElement.style.display = "none";
}
}
function buildTable(labels, objects, container) {
container.innerHTML = '';
var table = document.createElement('table');
// class table
table.classList.add("cartTable");
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
var theadTr = document.createElement('tr');
for (var i = 0; i < labels.length; i++) {
var theadTh = document.createElement('th');
theadTh.classList.add("cartTh");
theadTh.setAttribute("colSpan", "2");
theadTh.style.padding = '12px';
theadTh.innerHTML = labels[i];
theadTr.appendChild(theadTh);
}
thead.appendChild(theadTr);
table.appendChild(thead);
for (j = 0; j < objects.length; j++) {
var tbodyTr = document.createElement('tr');
for (k = 0; k < labels.length; k++) {
var tbodyTd = document.createElement('td');
tbodyTd.classList.add("cartTd");
tbodyTd.setAttribute("colSpan", "2");
tbodyTd.style.padding = '12px';
if (labels[k] === "Quantity") {
var qinput = document.createElement('input');
qinput.setAttribute("type", "number");
qinput.setAttribute("min", "0");
qinput.setAttribute("max", "10");
qinput.setAttribute("id", "quantityInput");
qinput.setAttribute("value", objects[j][labels[k].toLowerCase()]);
tbodyTd.appendChild(qinput);
} else {
tbodyTd.innerHTML = objects[j][labels[k].toLowerCase()];
}
tbodyTr.appendChild(tbodyTd);
}
tbody.appendChild(tbodyTr);
}
table.appendChild(tbody);
var tfoot = document.createElement('tfoot');
var footTr = document.createElement('tr');
var footTh = document.createElement('th');
var footTd = document.createElement('td');
footTd.setAttribute("id", "totalElement")
tbodyTd.setAttribute("colSpan", "3");
footTh.setAttribute("colSpan", "4");
footTd.innerHTML = Total;
footTh.innerHTML = 'TOTAL';
footTd.classList.add("cartTd");
footTd.classList.add("footerTable");
footTh.classList.add("cartTh");
footTr.appendChild(footTh);
footTr.appendChild(footTd);
tfoot.appendChild(footTr);
table.appendChild(tfoot);
container.appendChild(table);
var beforeText = document.createElement("p");
beforeText.style.marginTop = '5px';
beforeText.innerHTML = "Requests";
container.appendChild(beforeText);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.style.width = '100%';
input.style.padding = '6px';
input.setAttribute("placeholder", "No onion, no tomato...");
container.appendChild(input);
}
I solved a similar problem by creating a rowid and when the user clicks into the row I check for changes. Here the main idea
tableRow.setAttribute("id", "row" + idTable + "_" + tableRow.rowIndex); // for easy handling and selecting rows
tableRow.addEventListener("click", function(){ ... here check for what ever change});
You could also go for a specific change in just one cell, so attach the eventlistener to each quantity cell and read the new value, validate and update other fields then
qinput.addEventListener("change", function(){ ... here check for what ever the change triggers });
EDIT fortheOP:
A generic example for adding an event listener to a tablerow this marks the selected table line red (class table-danger) and removes the colour from allother previous selected lines:
tableRow.addEventListener("click", function(){
tRowData = [];
if(this.classList.contains("table-danger")) {
this.classList.remove("table-danger");
return;
} else {
var nodeParent = this.parentNode;
var trows= nodeParent.getElementsByTagName("tr");
for(var i = 0; i < trows.length;i++) {
trows[i].classList.remove("table-danger");
}
this.classList.add("table-danger");
var cells = this.getElementsByTagName("td");
for ( i = 0; i < cells.length; i++) {
tRowData.push(cells[i].innerHTML); // e.g.: Here you could place your update routine
}
tRowData.push(this.getAttribute("id"));
tRowData.push(this.rowIndex);
return tRowData;
}
});
function addrow() {
debugger;
var person = [];
if (localStorage.person1 != null && localStorage.person1 !=undefined) {
var person = JSON.parse(localStorage.person1);
}
var name = document.getElementById('name').value;
var city = document.getElementById('city').value;
person.push({
pname: name,
pcity: city
});
localStorage.setItem('person1', JSON.stringify(person));
bind();
}
function bind() {
debugger;
var per_list = JSON.parse(localStorage.getItem('person1'));
for (i = 0; i < per_list.length; i++ ) {
var table = document.getElementById('ptable');
var row = table.insertRow(0);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML = per_list[i].pname;
col2.innerHTML = per_list[i].pcity;
}
}
I have two fields name and city;Now, click on "add row" prints ok for first value, but afterwards it is printing both old and new value.. And, i want only new entry below the old input.. thanks in advance
You need to clear the table since you are showing all the elements in the .bind function.
function bind() {
debugger;
var per_list = JSON.parse(localStorage.getItem('person1'));
// clear the table
var table = document.getElementById('ptable');
for (var i = 0, rows = table.rows.length; i < rows; i++) {
table.deleteRow(0)
}
// fill the table
for (i = 0; i < per_list.length; i++) {
var row = table.insertRow(0);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML = per_list[i].pname;
col2.innerHTML = per_list[i].pcity;
}
}
I have to validate a table column using javascript.But I am not able to get row wise column value.I am generating this table using java script function like add row and add column. I have to submit data to insert into database .Before submission I have to check quantity and perunit price should be numeric value.
But I am not able to apply appropriate javascript API to get particular row wise column value.
please check this image
I am posting the code for what i did
<script language="javascript">
// Add row to the HTML table
function addRow() {
var table = document.getElementById('my_table'); //html table
var rowCount = table.rows.length; //no. of rows in table
var columnCount = table.rows[0].cells.length; //no. of columns in table
var row = table.insertRow(rowCount); //insert a row
var cell1 = row.insertCell(0); //create a new cell
var element1 = document.createElement("input"); //create a new element
element1.type = "checkbox"; //set the element type
element1.setAttribute('id', 'newCheckbox'); //set the id attribute
element1.setAttribute('checked',true); //set the id attribute
cell1.appendChild(element1); //append element to cell
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.setAttribute('id', 'newInput'); //set the id attribute
element2.setAttribute('name', 'sl'+rowCount);
element2.setAttribute('style', 'width: 50px');
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "textarea";
element3.setAttribute('rows', '4');
element3.setAttribute('cols','40');
element3.setAttribute('id', 'newInput'); //set the id attribute
element3.setAttribute('name', 'discription'+rowCount);
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.setAttribute('id', 'newInput'); //set the id attribute
element4.setAttribute('name', 'quantity'+rowCount);
cell4.appendChild(element4);
var cell5 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.setAttribute('id', 'newInput'); //set the id attribute
element5.setAttribute('name', 'price'+rowCount);
cell5.appendChild(element5);
var cell6 = row.insertCell(5);
var element6 = document.createElement("input");
element6.type = "text";
element6.setAttribute('id', 'newInput'); //set the id attribute
element6.setAttribute('name', 'CST'+rowCount);
element6.setAttribute('style', 'width: 50px');
cell6.appendChild(element6);
var cell7 = row.insertCell(6); //create a new cell
var element7 = document.createElement("input"); //create a new element
element7.type = "checkbox"; //set the element type
element7.setAttribute('id', 'vat5'); //set the id attribute
element7.setAttribute('name','tax'+rowCount);
element7.setAttribute('value','vat5');
cell7.appendChild(element7);
var cell8 = row.insertCell(7); //create a new cell
var element8 = document.createElement("input"); //create a new element
element8.type = "checkbox"; //set the element type
element8.setAttribute('id', 'vat14'); //set the id attribute
element8.setAttribute('name','tax'+rowCount);
element8.setAttribute('value','vat14') ;
cell8.appendChild(element8);
var cell9 = row.insertCell(8); //create a new cell
var element9 = document.createElement("input"); //create a new element
element9.type = "checkbox"; //set the element type
element9.setAttribute('id', 'serviceTax'); //set the id attribute
element9.setAttribute('name','tax'+rowCount);
element9.setAttribute('value','serviceTax');
cell9.appendChild(element9);
}
//Alert
// delete the selected rows from table
function deleteSelectedRows() {
var table = document.getElementById('my_table'); //html table
var rowCount = table.rows.length; //no. of rows in table
for(var i=0; i< rowCount; i++) { //loops for all row in table
var row = table.rows[i]; //return a particular row
var chkbox = row.cells[0].childNodes[0]; //get check box object
if(null != chkbox && true == chkbox.checked) { //wheather check box is selected
table.deleteRow(i); //delete the selected row
rowCount--; //decrease rowcount by 1
i--;
}
}
}
// append column to the HTML table
function addColumn() {
var tblHeadObj = document.getElementById('my_table').tHead; //table head
for (var h=0; h< tblHeadObj.rows.length; h++) {
var newTH = document.createElement('th');
tblHeadObj.rows[h].appendChild(newTH); //append ne th to table
newTH.innerHTML = 'Column '+ (tblHeadObj.rows[h].cells.length); //append th content to th
}
var tblBodyObj = document.getElementById('my_table').tBodies[0]; //table body
for (var i=0; i< tblBodyObj.rows.length; i++) {
var newCell = tblBodyObj.rows[i].insertCell(-1); //create new cell
newCell.innerHTML = 'cell '+ (tblBodyObj.rows[i].cells.length); //append data to cell
}
}
// delete table rows with index greater then 0
function deleteAllRows() {
var tbl = document.getElementById('my_table'); // table reference
lastRow = tbl.rows.length - 1; // set the last row index
// delete rows with index greater then 0
for (i = lastRow; i > 0; i--) {
tbl.deleteRow(i); //delete the row
}
}
// delete last table column
function deleteColumn() {
var allRows = document.getElementById('my_table').rows;
for (var i=0; i< allRows.length; i++) {
if (allRows[i].cells.length > 3) {
allRows[i].deleteCell(-1); //delete the cell
} else {
alert("You can't delete more columns.");
return;
}
}
}
function generate(){
var table = document.getElementById('my_table');
var rowCount = table.rows.length;
var f = document.form;
f.target = "_blank";
f.method="post";
f.action='ViewPO.jsp?rowCount='+rowCount;
f.submit();
}
function generate1(){
var table = document.getElementById('my_table');
var rowCount = table.rows.length;
document.write(rowCount)
var a;
var b=document.myform.punitprice.value;
var c=document.myform.ptax.value;
var regexLetter = /[a-zA-z]/;
for(var j=1;i<=rowcount;i++){
var oCells = table.rows.item(j).cells;
a=oCells[3].firstChild.data;
}
if(regexLetter.test(a)){
alert('Enter Only Numeric Values For ');
return false;
}
var f = document.form;
f.target = "";
f.method="post";
f.action='purchaseAction.jsp?rowCount='+rowCount;
// f.submit();
}
</script>
<table id="my_table" align="center" border="2" cellpadding="0" cellspacing="0">
<thead><tr>
<th>Select</th>
<th>Sl.no</th>
<th>Description of Services/Goods</th>
<th>Quantity</th>
<th>Price/Unit</th>
<th>CST %</th>
<th>VAT5.5%</th>
<th>VAT14.5%</th>
<th>ServiceTax%</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br>
</center>
<center>
<hr/>
<bgcolor ="red"/>
<input type="button" value="Add row" name="add" onClick="addRow()"/>
<input type="button" value="Delete selected rows" name="delete_all" onClick="deleteSelectedRows()" />
<input type="button" value="Delete all rows" name="delete" onClick="deleteAllRows()" /><br/>
<hr/>
<p>
<input type="submit" value="Save" onclick="generate1()" />
<input type="submit" value="View PO" onclick="generate()"/>
</center>
<hr/>
</form>
</div>
Help me as soon as possible.
I am trying to build a form for creating a list for image deployment.
I am able to create a dynamic table on form load and also collect the data for each value, but can seem to get the Add and Delete working.
My Question:
What must I do(or change) in my code to get the ADD and Delete options working and to export the table data in CSV format.
Please could someone help and/or guide me as I am getting so lost and really would like a working example .. there is so much on the net it's over-whelming
Newest place I visited is Mozilla DOM help pages what's confusing is how to load your own variables into the table
For reference I used stackoverflow and plenty google and finally this site
Here is my code:
<div id="metric_results">
Enter Target Name:
<input type="text" name="textbox1" id="textbox1" VALUE="win2k8"/>
<br>
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
<input type="button" id="create" value="Add Row" onclick="Javascript:addRow()">
<input type="button" id="create" value="Delete Row" onclick="Javascript:deleteRow()">
</div>
<SCRIPT LANGUAGE="JavaScript">
window.onload =addTable;//loads table on window loading
function addTable() {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
var imageName = textbox1.value
table.border = '1'
table.appendChild(tableBody);
var heading = new Array();
heading[0] = "imageName"
heading[1] = "acceptAllEula"
heading[2] = "noSSLverify"
heading[3] = "noVerification"
heading[4] = "TargetImagelocation"
heading[5] = "Username"
heading[6] = "Password"
heading[7] = "Target IP"
var imageInfo = new Array()
imageInfo[0] = new Array(imageName, "acceptAllEula", "noSSLverify", "noVerification", "testLocation", "user", "pass", "192.168.1.151")
imageInfo[1] = new Array("win2008", "acceptAllEula", "noSSLverify", "noVerification", "testLocation", "user", "pass", "192.168.1.151")
//TABLE COLUMNS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < heading.length; i++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[i]));
tr.appendChild(th);
}
//TABLE ROWS
for (i = 0; i < imageInfo.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < imageInfo[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(imageInfo[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table)
}
function addRow() {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
</SCRIPT>
You're not setting any id to the table you're creating onload - so when you later come to call getElementById() inside addRow it cannot be found (and you're using a variable which does not exist - tableID!)
My suggestion is to take an id as a parameter to addTable, and set that as the id of the dynamically generated table:
function addTable(id) {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
table.id = id;
....
onload, pass somethig sensible - default perhaps:
window.onload = function(){
addTable("default");
}
And either pass this in when adding a row, or use the default provided above:
function addRow() {
var table = document.getElementById("default");
....
or
function addRow(id) {
var table = document.getElementById(id);
Updated fiddle: https://jsfiddle.net/egtu5kay/5/
Left as an exercise for you: Correctly formatting the new row as you wish.
I have this table:
The table has data from every month, but only shows the selected date.
So, the question is: How can I do a total of Actual Hours and Extra Hours per month (visible data)?
This is how I build the table:
var total = 0 ;
var actualTotal = 0 ;
var totalEH = 0;
var table=document.getElementById("fbody");
for (var i=0;i<user.length;i++)
{
var row=table.insertRow(-1);
var cellDate = row.insertCell(-1);
var cell2 = row.insertCell(-1);
var cell3 = row.insertCell(-1);
var cell4 = row.insertCell(-1);
var cell5 = row.insertCell(-1);
var cell7 = row.insertCell(-1);
var cell8 = row.insertCell(-1);
var startAM = user[i].reg_start_worktime_am;
var finishAM = user[i].reg_finish_worktime_am;
var startPM = user[i].reg_start_worktime_pm;
var finishPM = user[i].reg_finish_worktime_pm;
cellDate.innerHTML = user[i].reg_date;
cell2.innerHTML = user[i].reg_start_worktime_am;
cell3.innerHTML = user[i].reg_finish_worktime_am;
cell4.innerHTML = user[i].reg_start_worktime_pm;
cell5.innerHTML = user[i].reg_finish_worktime_pm;
cell7.innerHTML = calcTimeDifference(startAM.substring(0,2), startAM.substring(3,5), finishAM.substring(0,2), finishAM.substring(3,5), startPM.substring(0,2), startPM.substring(3,5), finishPM.substring(0,2), finishPM.substring(3,5));
cell8.innerHTML = (calcTimeDifference(startAM.substring(0,2), startAM.substring(3,5), finishAM.substring(0,2), finishAM.substring(3,5), startPM.substring(0,2), startPM.substring(3,5), finishPM.substring(0,2), finishPM.substring(3,5))-user[i].worktime_fullhours).toFixed(2);
if (cell8.innerHTML != "NaN")
{
totalEH += parseFloat((calcTimeDifference(startAM.substring(0,2), startAM.substring(3,5), finishAM.substring(0,2), finishAM.substring(3,5), startPM.substring(0,2), startPM.substring(3,5), finishPM.substring(0,2), finishPM.substring(3,5))-user[i].worktime_fullhours).toFixed(2));
total = (document.getElementById('box-table-a').rows.length-1)*user[0].worktime_fullhours;
actualTotal += parseFloat(calcTimeDifference(startAM.substring(0,2), startAM.substring(3,5), finishAM.substring(0,2), finishAM.substring(3,5), startPM.substring(0,2), startPM.substring(3,5), finishPM.substring(0,2), finishPM.substring(3,5)));
}
}
Thanks
EDIT:
Fixed:
var totalActuals = 0,
totalExtras = 0;
var totalHours = 0;
var trs = $("#fbody tr").each(function(e) {
if($(this).css('display')!='none')
if( $("td:eq(6)", this).text() != 'NaN' ) {
// alert("Horro! "+$("td:eq(6)", this).text() );
totalActuals += parseFloat( $("td:eq(5)", this).text() );
totalExtras += parseFloat($("td:eq(6)", this).text());
totalHours++;
}
});
totalHours = totalHours*8;
If I understand you correctly, your table will have some rows that are visible, and some will be hidden. And, you want to calculate the totals for rows that are visible.
You can do this by looping through only the visible rows and accessing the columns required for calculating the totals.
var totalActuals = 0;
var totalExtras = 0;
$.each($('table tr:visible',function() {
totalActuals += $(this).find(".actualHours").val();
totalExtras += $(this).find(".totalExtras").val();
};)
But this will also return the header row. So I think you should assign a class to the rows of the table, and use the class in the jquery selector - $('table .tableRow:visible')
Edit
Here I had assumed that you have given the class "actualHours", "totalExtras" to the div's in which the actual hours and total extra hours are shown in each row of the table. If you haven't done so, you can use -
totalActuals += $(this).find("td").eq(5).text();
totalActuals += $(this).find("td").eq(6).text();
This will select the 5th and 6th columns of the row.