Delete Row, Save Changes once I edit table using Javascript - javascript

Someone posted this:
Making row editable when hit row edit button
I wanted to create one delete/edit/save button so that person can enter the order number and delete or edit the data.
Sequencing steps:
On Delete:
I click delete button, the prompt box comes up, I enter 1, it deletes 1.
I click delete button, the prompt box comes up, I enter 2, it does not delete 2.
However:
I click delete button, the prompt box comes up, I enter 2, it deletes 2.
I click delete button, the prompt box comes up, I enter 1, it does not delete 1.
Edit Button works, but when I click on the save button, it won't save the changes
https://jsfiddle.net/nhgjdr00/8/
HTML:
<table id="myTable" border="1">
<thead>
<th>Order #</th>
<th>Name</th>
<th>Tea Order</th>
<th>Tea Size</th>
</thead>
<tbody>
<tr>
<td class="rowNumber">1</td>
<td>Shakespeare</td>
<td>Iced</td>
<td>Small</td>
</tr>
<tr>
<td class="rowNumber">2</td>
<td>Frost</td>
<td>Hot</td>
<td>Medium</td>
</tr>
</tbody>
</table>
<br>
<input id="deleteRowBtn" type="button" value="Delete Row" />
<input id="editBtn" type="button" value="edt" />
<input id="saveBtn" type="button" value="saveChange" />
<br>
<br>
<form name="create"2 style="width:80px;">
Name:<input type="text" id="txtname" />
<br>
Tea Order:<input type="text" id="txtTeaOrder" name="txtTeaOrder" />
<br>
Tea Size<input type="text" id="txtTeaSize" name="txtTeaSize" />
<br>
</form>
</body>
JS:
"use strict";
var orderNumberHolder=[]; // holds each order number
// returns a html element (id)
var $ = function(id) {
return document.getElementById(id);
};
function deleteRow() {
var orderNumber = parseInt(prompt ("enter order number to delete"));
if (orderNumber == NaN || orderNumber < 1) {
prompt ("enter order number");
} else {
var table = $("myTable");
var rowCount = table.rows.length; // eliminate header so minus 1
for(var i=0, j=0; i<rowCount; i++, j++) {
var row = table.rows[i];
if (orderNumber == i) {
table.deleteRow(i);
rowCount--;
table.rows[j].cells[0].innerHTML = j; // renumbers the list after delete row
}
}
}
}
function edt() {
// converts number into integer
var orderNumber = parseInt(prompt ("enter order number to edit"));
// need to store order number so I can reference when I save edit info
orderNumberHolder.push(orderNumber);
if (orderNumber == NaN || orderNumber < 1) {
prompt ("enter order number");
} else {
var table = $("myTable");
var rowCount = table.rows.length;
// i is index, so start with 1 so it doesn't include header
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
if (orderNumber == i){
$("txtname").value = table.rows[i].cells["1"].innerHTML;
$("txtTeaOrder").value = table.rows[i].cells["2"].innerHTML;
$("txtTeaSize").value = table.rows[i].cells["3"].innerHTML;
}
}
}
}
function saveChange() {
var table = $("myTable");
var rowCount = table.rows.length; // do not want to include header
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
if (orderNumberHolder[i] == i){
table.rows[i].cells["1"].innerHTML = $("txtname").value ;
table.rows[i].cells["2"].innerHTML = $("txtauthor").value;
table.rows[i].cells["3"].innerHTML = $("txtcdate").value;
$("txtname").value = '';
$("txtauthor").value = '';
$("txtcdate").value = '' ;
rowCount--;
}
}
}
window.onload = function() {
$("deleteRowBtn").onclick = deleteRow; // calls function
$("editBtn").onclick = edt; // calls function
$("saveBtn").onclick = saveChange; // calls function
}
I would appreciate any suggestions.

You are taking the row number and deleting that row. When u delete the first row then row number of existing element ie (order# 2) changes to 1 from 2. Hence when you enter 2 in prompt there is no such row to delete.

Related

How to create labels and text boxes dynamically

Im suppose to create text boxes dynamically for x amount of courses that the user inputs. Each course, the user has to put "Course Title, and Mark Recieved". So lets say the user is taking 3 courses this semester. I need to make it so that theres 6 text boxes with the title of Course Title, and Mark Recieved for every two text box. Im not sure how to do this
<table id="textbox">
<tr>
<td>
<input type="button" onclick="addFunction()" value="Add"/>
</td>
</tr>
</table>
<script>
function addFunction() {
var table = document.getElementById("textbox");
var rowlen = table.rows.length;
var row = table.insertRow(rowlen);
row.id=rowlen;
var arr = [ 'textboxfiledname' ]
for (i = 0; i < 2; i++) {
var x = row.insertCell(i)
if (i == 1) {
x.innerHTML = "<input type='button' onclick='removeCell(" + row.id+ ")' value=Delete>"
} else {
x.innerHTML = "<label>"+arr[i]+"</label><input type='textbox' name='"+arr[i]+"'>"
}
}
}
function removeCell(rowid) {
var table = document.getElementById(rowid).remove();
}
</script>

Add rows and data

So currently I can add rows with this code:
function addRow(){
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createTextNode('New row')
newCell.appendChild(newText);
}
Here is my table:
<table id="myTable" border="2px">
<tbody>
<td>
Module 1
</td>
<td>
Introduction
</td>
<td id="info">
</td></tr>
<tr>
<td>
<div id="button"> Add Another Row </div>
</td></tr>
</tbody>
</table>
Here is how I add data to the row:
function showChoices()
{
//retrieve data
var selLanguage = document.getElementById("productchoice3");
//set up output string
var result="<ul> \n";
//step through options
for (i = 0; i < selLanguage.length; i++)
{
//examine current option
currentOption = selLanguage[i];
//print it if it has been selected
if (currentOption.selected == true)
{
console.log(currentOption.label);
result += " <li>" + currentOption.label + "<br>" + currentOption.value + "<\/li> \n";
} // end if
} // end for loop
//finish off the list and print it out
result += "<\/ul> \n";
output = document.getElementById("info");
output.innerHTML = result;
document.getElementById('info').style.display='block';
}
What I want to do is have the "add another row" move down each time I click it, so I can add infinite rows, and have a way to add data to the newest row that was created.
You could easily add an id to the row, by doing:
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.id = "whateverYouWant";

Add table values to input field on button click

I have a DataTable that stores names only. I want to have a button that will add all the names in the DataTable to an text input field.
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<thead>
<tr>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>chris</td>
</tr>
<tr>
<td>mike</td>
</tr>
</tbody>
</table>
<button id="add" >ADD</button>
<input type="text" id="text">
</div>
After click the "add" button, I want the names to appear in the text field separated by a comma.
And if possible, If the button is clicked again, remove the names?
I created the whole solution on codepen. This is the function used:
var clicks = 0;
function csv() {
var box = document.getElementsByName('text')[0];
if(clicks === 0){
var newcsv = "";
var tds = document.getElementsByTagName("TD");
for(var i = 0; i < tds.length; i++)
{
newcsv += tds[i].innerHTML;
if(i != tds.length-1) newcsv += ",";
}
box.value = newcsv;
clicks++;
}
else{
clicks = 0;
box.value = "";
}
}
This is bound to onclick event of a button.
Assign id to input
<input type=text id="textbox"/>
Just loop though table
var table = document.getElementById("mytab1");
var textbox=document.getElementById("textbox")
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
if(textbox.value=="")
{
textbox.value=row.cells[j].innerText;
}
else
{
textbox.value+= textbox.value+','+row.cells[j].innerText;
}
}
}

Delete html Row and Delete Column button using Javascript

I am trying to achieve like the pic below:
I don't seem to get the "delete selected column" right and also Delete selected row; instead the are deleting all rows and all columns.
So far I have the following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
//*********************************Start Add Row **********************************************************
function addRowToTable(){
var tbl = document.getElementById('tbl_sales'); //html table
var columnCount = tbl.rows[0].cells.length; //no. of columns in table
var rowCount = tbl.rows.length; //no. of rows in table
var row = tbl.insertRow(rowCount); //insert a row method
// For Every Row Added a Checkbox on first cell--------------------------------------
var cell_1 = row.insertCell(0); //Create a new cell
var element_1 = document.createElement("input"); //create a new element
element_1.type = "checkbox"; //set element type
element_1.setAttribute('id','newCheckbox'); //set id attribute
cell_1.appendChild(element_1); //Append element to created cell
// For Every Row Added add a Select box on Second cell------------------------------
var cell_2 = row.insertCell(1);
var element_2 = document.createElement('select');
element_2.name = 'SelDist' + rowCount;
element_2.options[0] = new Option('John Doe', 'value0');
element_2.options[1] = new Option('Dane Doe', 'value1');
cell_2.appendChild(element_2);
// For Every Row Added add a textbox on the rest of the cells starting with the 3rd,4th,5th... coloumns going on...
if(columnCount >= 2){ //Add cells for more than 2 columns
for (var i=3; i<=columnCount; i++) {
var newCel = row.insertCell(i-1); //create a new cell
var element_3 = document.createElement("input");
element_3.type = "text";
element_3.setAttribute('id', 'newInput'); //set the id attribute
newCel.appendChild(element_3);
}
}
}
//***************************** End Add Row ***************************************************************
// *****************************Start Add Column**********************************************************
function addColumn() {
var tblBodyObj = document.getElementById('tbl_sales').tBodies[0];
var rowCount = tblBodyObj.rows.length;
//for every Coloumn Added Add checkbox on first row ----------------------------------------------
var newchkbxcell = tblBodyObj.rows[0].insertCell(-1);
var element_4 = document.createElement("input");
element_4.type = "checkbox";
element_4.setAttribute('id','newCheckbox');
newchkbxcell.appendChild(element_4);
//For Every Coloumn Added add Drop down list on second row-------------------------------------
var newselectboxcell = tblBodyObj.rows[1].insertCell(-1);
var element_5 = document.createElement('select');
element_5.name = 'SelProd' + rowCount;
element_5.options[0] = new Option('Product11', 'value0');
element_5.options[1] = new Option('Product12', 'value1');
element_5.options[2] = new Option('Product13', 'value2');
element_5.options[3] = new Option('Product14', 'value3');
element_5.options[4] = new Option('Product15', 'value4');
element_5.options[5] = new Option('Product16', 'value5');
newselectboxcell.appendChild(element_5);
// For Every Coloumn Added add a textbox on the rest of the row cells starting with the 3rd,4th,5th......
for (var i=2; i< tblBodyObj.rows.length; i++) { //Add cells in all rows starting with 3rd row
var newCell = tblBodyObj.rows[i].insertCell(-1); //create new cell
var element_6 = document.createElement("input");
element_6.type = "text"
element_6.setAttribute('id', 'Newinput');
newCell.appendChild(element_6)
}
}
//*****************************Start Delete Selected Rows **************************************************
function deleteSelectedRows() {
var tb = document.getElementById('tbl_sales');
var NoOfrows = tb.rows.length;
for(var i=0; i< NoOfrows; i++) {
var row = tb.rows[i];
var chkbox = row.cells[0].childNodes[0]; //get check box object
if(null != chkbox && true == chkbox.checked) { //wheather check box is selected
tb.deleteRow(i); //delete the selected row
NoOfrows--; //decrease rowcount by 1
i--;
}
}
}
//*****************************End Delete Selected Columns **************************************************
//*****************************Start Delete Selected Columns ************************************************
function deleteSelectedColoumns()
{
var tb = document.getElementById('tbl_sales');//html table
var NoOfcolumns = tb.rows[0].cells.length; //no. of columns in table
for (var clm=3; clm< NoOfcolumns; clm++)
{
var rw = tb.rows[0];
var chkbox = rw.cells[clm].childNodes[0];
if(null != chkbox && true == chkbox.checked)
{
//-----------------------------------------------------
var lastrow = document.getElementById('tbl_sales').rows;
for (var x=0; x< lastrow.length; x++)
{
lastrow[x].deleteCell(clm);
}
//-----------------------------------------
NoOfcolumns--;
clm--;
}else
{
alert ("not selected");
return;
}
}
}
//*****************************End Delete Selected Columns **************************************************
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Distributor Sales</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<table width="30" border="1" id="tbl_sales">
<tr>
<td></td>
<td><strong>Products</strong></td>
<td><input type="button" name="adclmbutton" id="addclmnbutton" value="Add Product" onclick="addColumn()" /></td>
</tr>
<tr>
<td><strong>Distributors</strong></td>
<td><strong>Sales Grid</strong></td>
<td><select name="select3" id="select">
<option>Product 1</option>
<option>Product 2</option>
<option selected="selected">Product 3</option>
</select></td>
</tr>
<tr>
<td><input type="button" name="addrowbutton" id="adrwbutton" value="Add Distributor" onclick="addRowToTable();"/></td>
<td><select name="select6" id="select6">
<option selected="selected">Jhon Doe</option>
<option>Jane Doe</option>
<option>David</option>
<option>Kelvin</option>
</select></td>
<td><label for="textfield"></label>
<input type="text" name="textfield" id="textfield" width="50px" /></td>
</tr>
</table>
<p>
<input type="submit" name="button3" id="button3" value="Remove Selected Distributor" onClick="deleteSelectedRows()"/>
<input type="submit" name="button4" id="button4" value="Remove Selected Product" onClick="deleteSelectedColoumns()"/>
</p>
</form>
</body>
</html>
Change this line:
lastrow[x].deleteCell(clm);
to
tb.rows[x].deleteCell(clm);
and also remove the branch
//} else { alert ("not selected"); return; }
,then it works well. Tested it here.
Your deleteSelectedColumns function will always return after passing a column which is not selected:
/*...*/
if(null != chkbox && true == chkbox.checked)
{
/*...*/
}else
alert ("not selected");
return;
}
If the first column is not selected, for instance, none of the others will be looked at.
You are also using submit buttons to trigger your functions. These will refresh the page when pressed (reseting it to its original state), giving the impression that all rows and columns have been deleted. Try using
<input type="button" />
instead.
if table is static, then you can use the below to delete first, last column:
var allRows = document.getElementById('destination').rows;
for(var i=0; i< allRows.length; i++) {
if (allRows[i].cells.length > 0) {
allRows[i].deleteCell(-1);// logic to remove the last column
allRows[i].deleteCell(0);// logic to remove the first column of the modified table.
}
}

Dynamically change table cell with user input in Javascript

This is what I'm trying to do: I have a table, created from Javascript with user input in each cell. This table is just to confirm that the data entered by the user is correct. If the user sees an error, they click on the cell which needs editing, and it puts a textbox in the table cell with the current cell data. The user will then be able to submit changes or discard the changes if they clicked on the wrong cell. This is currently what I have:
<table id = "confirm">
<tr><th>Firstname</th><td id = "txtFirstname" onclick = "update(this.id)">Adan</td></tr>
<tr><th>Lastname</th><td>Smith</td></tr>
<tr><th>Username</th><td>ASmith</td></tr>
<tr><th>Email</th><td>abc#123.com</td></tr>
<tr><th>Phone</th><td>123-456-7890</td></tr>
</table>
<script type = "text/javascript">
function update(id){
//Get contents off cell clicked
var content = document.getElementById(id).firstChild.nodeValue;
//Switch to text input field
document.getElementById(id).innerHTML = "<input type = 'text' name = 'txtNewInput' id = 'txtNewInput' value = '" + content + "'/>";
}
</script>
This is what my current code does: When user clicks on the cell, it replaces it with the current text inside a textbox, which is great, but when you try to edit the text, it calls the function over again replacing the text with "null". Please help me figure this out!
It is caused by event bubbling. You didn't want onclick to apply to input, but unfortunately this is not the case. To solve this problem, simply do this (taken from http://jsfiddle.net/DerekL/McJ4s/)
table td, th{
border: 1px solid black;
}
<table id="confirm">
<tr>
<th>Firstname</th>
<td contentEditable>Adan</td>
</tr>
<tr>
<th>Lastname</th>
<td>Smith</td>
</tr>
<tr>
<th>Username</th>
<td>ASmith</td>
</tr>
<tr>
<th>Email</th>
<td>abc#123.com</td>
</tr>
<tr>
<th>Phone</th>
<td>123-456-7890</td>
</tr>
</table>
Why do it with JavaScript when simple HTML can do the same thing? ;)
Internet Explorer:
There is a strange "bug" in IE that it won't allow a table cell to be editable (why, Microsoft?) So you have to wrap your content with a <div> (taken from http://jsfiddle.net/DerekL/McJ4s/3/):
table td,
th {
border: 1px solid black;
}
<table id="confirm">
<tr>
<th>Firstname</th>
<td>
<div contenteditable>Adan</div>
</td>
</tr>
<tr>
<th>Lastname</th>
<td>Smith</td>
</tr>
<tr>
<th>Username</th>
<td>ASmith</td>
</tr>
<tr>
<th>Email</th>
<td>abc#123.com</td>
</tr>
<tr>
<th>Phone</th>
<td>123-456-7890</td>
</tr>
</table>
<table id = "confirm">
<tr><th>Firstname</th><td id = "txtFirstname" onclick = "update(this.id)">Adan</td></tr>
<tr><th>Lastname</th><td>Smith</td></tr>
<tr><th>Username</th><td>ASmith</td></tr>
<tr><th>Email</th><td>abc#123.com</td></tr>
<tr><th>Phone</th><td>123-456-7890</td></tr>
</table>
<script type = "text/javascript">
function update(id){
//Get contents off cell clicked
var content = document.getElementById(id).firstChild.nodeValue;
//Switch to text input field
document.getElementById(id).innerHTML = "<input type = 'text' name = 'txtNewInput' id = 'txtNewInput' value = '" + content + "'/>";
}
</script>
Added an if statement in the update() function. Changed it to:
<script type = "text/javascript">
function update(id){
if(document.getElementById(id).firstChild != "[object HTMLInputElement]"){
//Get contents off cell clicked
var content = document.getElementById(id).firstChild.nodeValue;
//Switch to text input field
document.getElementById(id).innerHTML = "<input type = 'text' name = 'txtNewInput' id = 'txtNewInput' value = '" + content + "'/>";
}
}
</script>
That works like a charm!
var table = document.getElementById('');
var rowCount = table.rows.length;
var noRowSelected = 1;
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
break;
}
document.getElementById("").value = row.cells[1].innerHTML;
document.getElementById("").value = row.cells[2].innerHTML;
document.getElementById("").value = row.cells[3].innerHTML;
document.getElementById("").value = row.cells[4].innerHTML;
}
}
The Above Example the checkbox must be need for the each row.then we used this check box to get the current edit row values in the dynamic table. then to use the id for edit field to set valued got from the table.
Dynamically Change the Table Row Value:
var table = document.getElementById('');
var rowCount = table.rows.length;
var noRowSelected = 1;
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
break;
}
document.getElementById("").value = row.cells[1].innerHTML;
document.getElementById("").value = row.cells[2].innerHTML;
document.getElementById("").value = row.cells[3].innerHTML;
document.getElementById("").value = row.cells[4].innerHTML;
}
}
The Above Example the checkbox must be need for the each row.then we used this check box to get the current edit row values in the dynamic table.

Categories