Adding buttons to each row of a table to remove said row - javascript

just looking for a simple solution on solving this, Consider the the following code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript - Add HTML Table Row </title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<form>
<script>
function addRow()
{
// get input values
var name = document.getElementById('name').value;
var currentAge =
document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var Delete = document.getElementById('Delete').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length/2+1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = Delete;
function myFunction(){
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + " tr
elements in the table.";
}
</script>
</form>
</head>
<style>
table, th {
border: 1px solid black;
}
tbody td{
padding: 30px;
}
tbody tr:nth-child(odd){
background-color: #F4BC01;
color: #ABC412;
}
$("")
</style>
<body>
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete Entry
<button id="Delete" onclick="remove_update(event)">delete</button> //this button right here but in each row and not here. should remove said row
</th>
</tr>
</table>
</body>
</html>
What im trying to do is within cel 5 (delete entry) is to add a delete button to each row that is entered into the table that will remove that row but don't know how to go about this. Ideally would like to do this without the use of JQuery if possible, since i've not touched upon it as of yet.

You can use the rowIndex property to delete the row.
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
const index = table.rows.length;
var newRow = table.insertRow(index);
newRow.setAttribute('data-index', index);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.textContent = name;
cel2.textContent = currentAge;
cel3.textContent = Birthday;
cel4.textContent = carType;
cel5.innerHTML = '<button onclick="removeRow(this)" type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
function removeRow(evt) {
const deleteIndex = evt.parentElement.parentElement.rowIndex;
document.getElementById("table").deleteRow(deleteIndex);
}
table,
th {
border: 1px solid black;
}
tbody td {
padding: 30px;
}
tbody tr:nth-child(odd) {
background-color: #F4BC01;
color: #ABC412;
}
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete</th>
</tr>
</table>
</body>
</html>

What you should be doing is that you set the innerHTML of cel5 to a button, e.g.:
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
Then, you can simply add a click event listener on the table, and check if a click event has emitted from the button element. If it matches, you then delete the closest <tr> element:
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
See proof-of-concept example below:
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length / 2 + 1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/> Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/> Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Actions</th>
</tr>
</table>

In the head, add a function that understands rows and cells. Call some delete on a parent of a cell (Delete the <tr> in which the <td> is located at). then on the body add to each dynamic button an onClick event and set that function you created earlier ON.
You can use a script like this:
function deleteRow() {
var tableData = event.target.parentNode;
var tableRow = tableData.parentNode;
tableRow.parentNode.removeChild(tableRow);
}
In the button you create (dynamically or fixedly) you should add an onClick event. For example:
<tr>
<td>John Doe</td>
<td>$10,000</td>
<td><input type="submit" value="Delete" id="Delete" onclick="deleteRow()"></td>
</tr>

Related

My submited table does not show on the browser

I have a scoreboard where the user can enter the score and when the user presses the "Submit" button it will show a table that will contain the information that the user has entered. But when I try it in the browser, my table doesn't show the information that was entered in the previous form, it only show the table heading. Let me explain like below:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physical = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
var table = document.getElementById("tableScore");
var row = table.insertRow(i);
var number = row.insertCell(0);
var name = row.insertCell(1);
var math = row.insertCell(2);
var physics = row.insertCell(3);
var chemistry = row.insertCell(4);
var avg = row.insertCell(5);
number.innerHtml = i;
name.innerHtml = testScore.name;
math.innerHtml = testScore.math;
physics.innerHtml = testScore.physics;
chemistry.innerHtml = testScore.chemistry;
avg.innerHtml = testScore.avg;
i++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
In js code you have used innerHtml instead of innerHTML.
Updated code:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physical = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
var table = document.getElementById("tableScore");
var row = table.insertRow(i);
var number = row.insertCell(0);
var name = row.insertCell(1);
var math = row.insertCell(2);
var physics = row.insertCell(3);
var chemistry = row.insertCell(4);
var avg = row.insertCell(5);
number.innerHTML = i;
name.innerHTML = testScore.name;
math.innerHTML = testScore.math;
physics.innerHTML = testScore.physics;
chemistry.innerHTML = testScore.chemistry;
avg.innerHTML = testScore.avg;
i++;
}
#import url('https://fonts.googleapis.com/css2?family=Bree+Serif&family=Caveat:wght#400;700&family=Lobster&family=Monoton&family=Open+Sans:ital,wght#0,400;0,700;1,400;1,700&family=Playfair+Display+SC:ital,wght#0,400;0,700;1,700&family=Playfair+Display:ital,wght#0,400;0,700;1,700&family=Roboto:ital,wght#0,400;0,700;1,400;1,700&family=Source+Sans+Pro:ital,wght#0,400;0,700;1,700&family=Work+Sans:ital,wght#0,400;0,700;1,700&display=swap');
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
</body>
</html>
When you use insertCell you need to use innerHTML or appendChild instead of the non-existent innerHtml
Also you do not need to have any integer in insertCell/Row
Also your HTML was invalid
number.appendChild(document.createTextNode(i));
name.appendChild(document.createTextNode(testScore.name));
math.appendChild(document.createTextNode(testScore.math));
physics.appendChild(document.createTextNode(testScore.physics));
chemistry.appendChild(document.createTextNode(testScore.chemistry));
avg.appendChild(document.createTextNode(testScore.avg));
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physics = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
var table = document.querySelector("#tableScore tbody");
var row = table.insertRow();
var number = row.insertCell();
var name = row.insertCell();
var math = row.insertCell();
var physics = row.insertCell();
var chemistry = row.insertCell();
var avg = row.insertCell();
number.appendChild(document.createTextNode(i));
name.appendChild(document.createTextNode(testScore.name));
math.appendChild(document.createTextNode(testScore.math));
physics.appendChild(document.createTextNode(testScore.physics));
chemistry.appendChild(document.createTextNode(testScore.chemistry));
avg.innerHTML = testScore.avg; // alternative to appendChild
i++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table border="2" id="tableScore">
<thead>
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</thead>
<tbody>
</tbody>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
You have some misspelled variables but you can also minimize your output with only one global innerHTML like in my example below:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physical = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
//MINIMIZED VERSION
document.getElementById("tableScore").innerHTML +=
"<td>" + i + "</td>" +
"<td>" + testScore.name + "</td>" +
"<td>" + testScore.math + "</td>" +
"<td>" + testScore.physical + "</td>" +
"<td>" + testScore.chemistry + "</td>" +
"<td>" + testScore.avg + "</td>";
i++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>

Access to input values created by javascript function

I have a form within a table with Title and description columns and the rows can be added dynamically by a button. I need to access and save the input values in text boxes created by javascript function when saving the form by save button. the input values are later saved on local storage. The saved values are used to repopulate the form in case of unsuccessful validation.
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title' + x + '" /></td>' +
'<td> <input type="text" id="description' + x + '" /></td></tr>';
}
function save_data() {
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows; i++) {
for (var j = 0; j < 2; j++) {
var title = document.getElementById('title' + i).value;
var desc = document.getElementById('description' + i).value;
var temp = {
title: title,
description: desc
};
data.push(temp);
}
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
did you mean something like this?
$(document).ready(()=>{
$('#container').append('<input id="addedTxt" type="text" />');
$('#addedTxt').val('Test');
$('#saveBtn').on('click', ()=>{
alert($('#addedTxt').val());
});
});
<div id="container">
</div>
<input id="saveBtn" type="button" value="save" />
(using jquery)
https://jsfiddle.net/u6vnxwzc/1/#&togetherjs=rQ2b5IsJQ1
or where is the problem?
In your code why you use the second For loop? I think it is not necessary.
find the working code snippet
https://s.codepen.io/mastersmind/debug/VNyKrY/DqADdKoRXEjA
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title'+x+'" /></td>'+
'<td> <input type="text" id="description'+x+'" /></td></tr>';
}
function save_data(){
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows-1; i++) {
var title = document.getElementById('title'+ i).value;
var desc = document.getElementById('description'+ i).value;
var temp = {title: title, description: desc};
data.push(temp);
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
loadData = function(){
let data = JSON.parse(window.localStorage.getItem('Table1'));
for(i=0; i<data.length;i++){
add_text_input();
document.getElementById('title'+ (i+1)).value = data[i].title;
document.getElementById('description'+ (i+1)).value = data[i].description;
}
}
loadData();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
</body>
</html>

How to delete a specific row in a table using javascript?

what i have implemented so far:
Enter the values in the input fields and click " Add" button , The entered values gets added to the new row .
And When i click delete button, all the rows are getting deleted .
What I need to implement :
Checkbox should get added to every row .
If i select the checkbox and click "delete" button, only that particular row should get deleted and it should work if i select multiple check boxes as well.
3.Clear the Input fields after i click add button .
Can anyone check this out and tell me how to do that .
//Javascript code to Add new rows onclick of a button and to delete row .
function addMoreRows() {
var user = document.getElementById('user_id').value;
var date = document.getElementById('date').value;
var color = document.getElementById('color').value;
var table = document.getElementById('tbl_id');
var row = table.insertRow();
var userName = row.insertCell(0);
var Date = row.insertCell(1);
var Color = row.insertCell(2);
var checkbox = row.insertCell(3);
userName.innerHTML = user;
Date.innerHTML = date;
Color.innerHTML = color;
}
function deleteMoreRows(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
table.deleteRow(i);
rowCount--;
i--;
}
}
<!-- HTML markup for the input fields and table . -->
<form align="center" method="GET">
Enter your name : <input type="text" name="users" id="user_id" value="name" onfocus="if(this.value == 'name') {this.value=''}" onblur="if(this.value == ''){this.value ='name'}"><br>
Select the Date : <input type="date" id="date"><br>
Select your favorite color:
<select id="color" required>
<option value="yellow">yellow</option>
<option value="red">red</option>
</select>
<br>
<br>
<input type="button" id="mysubmit" value="Add Row" onClick="addMoreRows()">
<input type="button" id="delete" value="Delete" onClick="deleteMoreRows('tbl_id')">
</form>
<br>
<br>
<table id="tbl_id" style="text-align:center" align="center" valign="top">
<thead>
<tr>
<th style="width:200px;">Name</th>
<th style="width:200px;">Date</th>
<th style="width:200px;">Color</th>
</tr>
</thead>
Let me know if this works for you:
//Javascript code to Add new rows onclick of a button and to delete row .
var rowId = 0;
function addMoreRows() {
var user = document.getElementById('user_id').value;
var date = document.getElementById('date').value;
var color = document.getElementById('color').value;
var table = document.getElementById('tbl_id');
var row = table.insertRow();
var rowBox = row.insertCell(0);
var userName = row.insertCell(1);
var Date = row.insertCell(2);
var Color = row.insertCell(3);
var checkbox = row.insertCell(4);
rowBox.innerHTML = '<input type="checkbox" id="delete' + getRowId() + '">';
userName.innerHTML = user;
Date.innerHTML = date;
Color.innerHTML = color;
}
function deleteMoreRows(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var selectedRows = getCheckedBoxes();
selectedRows.forEach(function(currentValue) {
deleteRowByCheckboxId(currentValue.id);
});
}
function getRowId() {
rowId += 1;
return rowId;
}
function getRowIdsFromElements($array) {
var arrIds = [];
$array.forEach(function(currentValue, index, array){
arrIds.push(getRowIdFromElement(currentValue));
});
return arrIds;
}
function getRowIdFromElement($el) {
return $el.id.split('delete')[1];
}
//ref: http://stackoverflow.com/questions/8563240/how-to-get-all-checked-checkboxes
function getCheckedBoxes() {
var inputs = document.getElementsByTagName("input");
var checkboxesChecked = [];
// loop over them all
for (var i=0; i < inputs.length; i++) {
// And stick the checked ones onto an array...
if (inputs[i].checked) {
checkboxesChecked.push(inputs[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
//ref: http://stackoverflow.com/questions/4967223/delete-a-row-from-a-table-by-id
function deleteRowByCheckboxId(CheckboxId) {
var checkbox = document.getElementById(CheckboxId);
var row = checkbox.parentNode.parentNode; //box, cell, row, table
var table = row.parentNode;
while ( table && table.tagName != 'TABLE' )
table = table.parentNode;
if (!table) return;
table.deleteRow(row.rowIndex);
}
<!-- HTML markup for the input fields and table . -->
<form align="center" method="GET">
Enter your name : <input type="text" name="users" id="user_id" value="name" onfocus="if(this.value == 'name') {this.value=''}" onblur="if(this.value == ''){this.value ='name'}"><br>
Select the Date : <input type="date" id="date"><br>
Select your favorite color:
<select id="color" required>
<option value="yellow">yellow</option>
<option value="red">red</option>
</select>
<br>
<br>
<input type="button" id="mysubmit" value="Add Row" onClick="addMoreRows()">
<input type="button" id="delete" value="Delete" onClick="deleteMoreRows('tbl_id')">
</form>
<br>
<br>
<table id="tbl_id" style="text-align:center" align="center" valign="top">
<thead>
<tr>
<th style="width:200px;">Delete</th>
<th style="width:200px;">Name</th>
<th style="width:200px;">Date</th>
<th style="width:200px;">Color</th>
</tr>
</thead>

how to insert generated html table data into database in php?

How I can insert all data from a generated HTML table into my database using PHP?
I have tried with a foreach loop, but it gives me an error all the time.
I have this code in JavaScript to adding a new row using a button:
var i=1;
function addRow()
{
var tbl = document.getElementById('table1');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var el = document.createElement('input');
el.type = 'text';
el.name = 'to' + i;
el.id = 'to' + i;
el.size = 40;
firstCell.appendChild(el);
var secondCell = row.insertCell(1);
var el2 = document.createElement('input');
el2.type = 'text';
el2.name = 'cost' + i;
el2.id = 'cost' + i;
el2.size = 40;
secondCell.appendChild(el2);
frm.h.value=i;
i++;
}
And this is my HTML code:
<table id="table1" width="40%" border="2" cellpadding="0" cellspacing="0">
<tr>
<td><strong>To Address</strong></td>
<td><strong>Delivery Cost</strong></td>
</tr>
<tr>
<td><input name="to" type="text" id="to" size="40"/></td>
<td><input name="cost" type="text" id="cost" size="40"/></td>
</tr>
</table>
<br/><br/>
<input style="float: right;background-color: #57a000;height: 30px;font-weight: bold; font-family: cursive;margin-left: 10px;"
type="submit" value="Save All" name="SaveCost"/>
<input style="float: right;background-color: #57a000;height: 30px;font-weight: bold; font-family: cursive;"
type="button" value="Add New Place" onclick="addRow();"/>
<input name="h" type="hidden" id="h" value="0"/>
Finally I want to write some PHP to insert all the data from the generated HTML table into my database.

add image input with jquery with limit to four

I have this code that a user can upload pictures. It works just fine, but the user can submit unlimited pictures, and I want to put a limit to four.
when the user reaches four input fields then they won't be allowed to add any input.
<script type="text/javascript">
function addItems()
{
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2)
table1.deleteRow(lastRow-1);
}
</script>
<form method="post" action="" enctype="multipart/form-data">
<table align="center" border="0" id="tab1">
<tr>
<td width="218" align="center">
<input type="file" name="image[]" /></td>
<td width="54" align="center">
<img src="Button-Add-icon.png" alt="Add" style="cursor:pointer"
onclick="addItems()" /></td>
<td>
<img src="Button-Delete-icon.png" alt="Remove" style="cursor:pointer"
onclick="remItems()" /></td>
</tr>
</table>
<table align="center" border="0" id="tab2">
<tr><td align="center">
<input type="submit" value="Upload" name="upload" /></td></tr>
</table>
</form>
Thanks
Add a global counter.. and check on your addItems function.. something like:
var totalItems = 0;
function addItems()
{
if(totalItems < 4) {
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
totalItems++; //increment the global counter...
} else {
//Display your message here.. with an alert or something...
}
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2) {
table1.deleteRow(lastRow-1);
totalItems--;
}
}

Categories

Resources