Delete table row with JavaScript? - javascript

I am adding some data with JavaScript with no problem but I wanted to delete a row by adding delete button inside the row which I add, but I couldn't do it. The code is below. The delete button doesn't work:
const ad = document.querySelector("#ad");
const soyad = document.querySelector("#soyad");
const yas = document.querySelector("#yas");
const ekle = document.querySelector("#ekle");
const liste = document.querySelector("#liste");
ekle.onclick = function() {
let tAd = document.createElement("td");
let tSoyad = document.createElement("td");
let tYas = document.createElement("td");
let tSil = document.createElement("td");
let silBtn = document.createElement("button");
silBtn.textContent = "Sil";
tAd.textContent = ad.value;
tSoyad.textContent = soyad.value;
tYas.textContent = yas.value;
let tr = document.createElement("tr");
tr.appendChild(tAd);
tr.appendChild(tSoyad);
tr.appendChild(tYas);
tr.appendChild(silBtn);
liste.appendChild(tr);
ad.value = "";
soyad.value = "";
yas.value = "";
ad.focus();
}
silBtn.onclick = function(e) {
tr.appendChild(tAd);
tr.appendChild(tSoyad);
tr.appendChild(tYas);
tr.appendChild(silBtn);
liste.removeChild(this.parentNode.parentNode);
}
<div id="sayfa">
<label for="">Ad:</label>
<input type="text" id="ad">
<label for="">Soyad</label>
<input type="text" id="soyad">
<label for="">Yas</label>
<input type="text" id="yas">
<button id="ekle">Tabloya Ekle</button>
<table id="liste">
<tr>
<th>Ad</th>
<th>SoyAd</th>
<th>Yaş</th>
<th>Sil</th>
</tr>
</table>
</div>

Use This Javascript
<script>
const ad=document.querySelector("#ad");
const soyad=document.querySelector("#soyad");
const yas=document.querySelector("#yas");
const ekle=document.querySelector("#ekle");
const liste=document.querySelector("#liste");
ekle.onclick=function(){
let tAd=document.createElement("td");
let tSoyad=document.createElement("td");
let tYas=document.createElement("td");
let tSil = document.createElement("td");
let silBtn =document.createElement("button");
silBtn.textContent="Sil";
tAd.textContent=ad.value;
tSoyad.textContent=soyad.value;
tYas.textContent=yas.value;
let tr=document.createElement("tr");
tr.appendChild(tAd);
tr.appendChild(tSoyad);
tr.appendChild(tYas);
tr.appendChild(silBtn);
liste.appendChild(tr);
ad.value="";
soyad.value="";
yas.value="";
ad.focus();
silBtn.onclick=function(e){
liste.removeChild(this.parentNode);
}
}
</script>

Related

Function needs double click to trigger

i have the following situation: i have to click twice on the button to trigger the function that adds the data into localStorage formular's content. Could you explain to me why is this button behaving like this and how can i remediate this problem?
here is the javascript code:
async function addMovieIntoBrowser() {
const valueName = document.getElementById("fname");
const valueDescription = document.getElementById("fdescription");
const valueYear = document.getElementById("fyear");
const valueRating = document.getElementById("frating");
const buttonInsert = document.getElementById("buttonInsert");
buttonInsert.onclick = async function () {
const name = valueName.value;
const description = valueDescription.value;
const image = await returnImage(name);
const year = valueYear.value;
const rating = valueRating.value;
if (name && description && image && year && rating) {
localStorage.setItem("Name", name);
localStorage.setItem("Description", description);
localStorage.setItem("Image", image);
localStorage.setItem("Year", year);
localStorage.setItem("Rating", rating);
localStorage.setItem("Date added", new Date().toLocaleString());
const table = document.getElementById("completedTable");
const row = table.insertRow(0);
const cell1 = row.insertCell(0);
const cell2 = row.insertCell(1);
const cell3 = row.insertCell(2);
const cell4 = row.insertCell(3);
const cell5 = row.insertCell(4);
const cell6 = row.insertCell(5);
cell1.innerHTML = localStorage.getItem("Name");
cell2.innerHTML = localStorage.getItem("Description");
cell3.innerHTML = localStorage.getItem("Image");
cell4.innerHTML = localStorage.getItem("Year");
cell5.innerHTML = localStorage.getItem("Rating");
cell6.innerHTML = localStorage.getItem("Date added");
const inputs = document.querySelectorAll(
"#fyear, #fname,#fdescription, #frating"
);
inputs.forEach((input) => {
input.value = "";
});
There is no need to use localStorage here as you are using the contents straight away on the same page. In fact, you can simplify your script considerably: Below is a short working example without the "image" column. As the film image seems to be supplied in form of a promise it can also be included by using await.
const inputs = [...document.querySelectorAll("#fyear, #fname,#fdescription, #frating")],
tbl=document.querySelector("#tbl");
document.querySelector("button").onclick=async ()=>{
tbl.insertAdjacentHTML("beforeend","<tr><td>"+
inputs.map(inp=>inp.value).join("</td><td>")+"</td></tr>");
inputs.forEach(inp=>inp.value="");
};
<form>
<input type="text" value="2020" id="fyear"> year<br>
<input type="text" value="Roma" id="fname"> name<br>
<input type="text" value="an epic film" id="fdescription"> description<br>
<input type="text" value="5" id="frating"> rating
</form><button>add</button>
<h2>Film table</h2>
<table><thead><tr><th>year</th><th>name</th><th>description</th><th>rating</th></tr></thread>
<tbody id="tbl"></tbody></table>
Even simpler
const tbl = document.getElementById("tbl"),
form = document.querySelector("form"),
inputs = [...form.elements];
document.querySelector("button").addEventListener("click",(e) => {
tbl.innerHTML += `<tr>${inputs
.map(({value}) => `<td>${value}</td>`)
.join("")}</tr>`;
form.reset();
});
<form>
<input type="text" value="" name="fyear"> year<br>
<input type="text" value="" name="fname"> name<br>
<input type="text" value="" name="fdescription"> description<br>
<input type="text" value="" name="frating"> rating
</form><button>add</button>
<h2>Film table</h2>
<table>
<thead>
<tr>
<th>year</th>
<th>name</th>
<th>description</th>
<th>rating</th>
</tr>
</thead>
<tbody id="tbl"></tbody>
</table>

How can I create a row which sums up the value of each column without knowing the row or column amount?

I have included my code below. I am creating a score keeping app and have created the basic score table where user can select player and round amount as well as add player names. I cant work out how to create a row to to sum every round for each player. I have tried several different ways but cant work it out. Any advice would be amazing! Have included code below.
<hr>
<body>
<div class="game-container">
<div class="row">
<div class="col-md-12">
<p>
<label>Enter number of players</label>
<br>
<input type="number" class="form-control" id="number-input" value="0" min="0">
<br>
<button id="makeTable">Go</button>
<table id="scoreTable">
</table>
<button id="addRound">Add Round</button>
<br>
<button id="totalValue">Sum Values</button>
</p>
</div>
</div>
</div>
</body>
<script>
/*Game page functionaility*/
let numberofRounds = 0;
// take number-input and make columns of it
function createColumns(){
const numberInput = document.getElementById('number-input');
const numberInputValue = numberInput.value;
const numberInputValueInt = parseInt(numberInputValue);
const scoreTable = document.getElementById('scoreTable');
topRow = document.createElement('tr');
topRow.setAttribute("id", "topRow");
scoreTable.appendChild(topRow);
const players = document.createElement('td');
players.innerHTML = "Players";
topRow.appendChild(players);
for(let i = 0; i < numberInputValueInt; i++){
const td = document.createElement('td');
td.innerHTML = `<input type="text" class="form-control" id="score-input">`;
topRow.appendChild(td);
}
document.getElementById('number-input').style.display = "none";
document.getElementById('makeTable').style.display = "none";
}
function addRound(){
const currentRound = +numberofRounds + 1;
numberofRounds = currentRound;
const roundNumber = "round_" + currentRound;
const numberInput = document.getElementById('number-input');
const numberInputValue = numberInput.value;
const numberInputValueInt = parseInt(numberInputValue);
const scoreTable = document.getElementById('scoreTable');
topRow = document.createElement('tr');
topRow.setAttribute("id", roundNumber);
scoreTable.appendChild(topRow);
const players = document.createElement('td');
players.innerHTML = currentRound;
topRow.appendChild(players);
for(let i = 0; i < numberInputValueInt; i++){
const td = document.createElement('td');
td.setAttribute("id", "round_"+currentRound+"_player_" + I);
td.innerHTML = `<input type="number" class="form-control" id="score-input"
value="0">`;
topRow.appendChild(td);
}
}
function addSumRow() {
if (!summedItems) {
const players = document.createElement('td');
}
}
// make event listener makeTable
document.getElementById("makeTable").addEventListener("click", function() {createColumns();});
document.getElementById("addRound").addEventListener("click", function() {addRound();});
document.getElementById("totalValue").addEventListener("click", function() {addSumRow();});
</script>

i have a form to input data in and i want the data to appear at another page from local storage

my problem is I console log the local storage and the inputs appear fine but I can't see them on the other page although at local storage they are stored fine
the form :
<form id="formID">
<div class="Contact__Card">
<div class="Input__Container">
<label for="foodName" class="Label" >Food</label>
<input
name="foodName"
class="Input"
type="text"
placeholder="What would you like to add?"
id="foodName"
required
/>
</div>
<div class="input__Container">
<label for="foodType">Choose Food type:</label>
<select class="Input" id="foodType" name="foodlist">
<option value="Fruit and vegetables">Fruit and vegetables</option>
<option value="Starchy food">Starchy food</option>
<option value="Dairy">Dairy</option>
<option value="Protein">Protein</option>
<option value="Fat">Fat</option>
</select></div>
<div class="Input__Container">
<label for="price" class="Label">price</label>
<input type="text" min="1" step="any" class="Input" id="foodPrice" required/>
</div>
<br>
<div class="Input__Container">
<input type="submit" value="Submit" class="Input"/>
</div>
</div>
</form>
the js file of the form page :
"use strict";
var allFood = [];
function food(foodName, foodType, price) {
this.foodName = foodName;
this.foodType = foodType;
this.price = price;
allFood.push(this);
}
food.prototype.fID = function () {
this.id = Math.floor(1111 + Math.random() * 9999);
};
const formEl = document.getElementById("formID");
formEl.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
event.preventDefault();
let foodName = event.target.foodName.value;
let foodType = event.target.foodType.value;
let price = event.target.foodPrice.value;
const newFood = new food(foodName, foodType, price);
newFood.fID();
saveData();
}
function saveData() {
let stringifiedData = JSON.stringify(allFood);
localStorage.setItem("Food", stringifiedData);
}
the table of the other page i want the data to apear in :
<table id="fTable">
<tr id="hdrTable">
</tr>
</table>
the js file of the output page is the issue from the get data function ?:
"use strict";
const fdTable = document.getElementById('fTable');
const tableHead = document.getElementById('hdrTable');
var allFood = [];
function food(foodName, foodType, price) {
this.foodName = foodName;
this.foodType = foodType;
this.price = price;
allFood.push(this);
}
food.prototype.fID = function () {
this.id = Math.floor(1111 + Math.random() * 9999);
};
table();
function table() {
let headerID = document.createElement("th");
headerID.textContent = "ID";
let headerName = document.createElement("th");
headerName.textContent = "Food Name";
let headerType = document.createElement("th");
headerType.textContent = "Type of Food";
let headerPrice = document.createElement("th");
headerPrice.textContent = "price";
hdrTable.appendChild(headerID);
hdrTable.appendChild(headerName);
hdrTable.appendChild(headerType);
hdrTable.appendChild(headerPrice);
}
food.prototype.Render = function () {
let row = document.createElement("tr");
let id = document.createElement("td");
let name = document.createElement("td");
let type = document.createElement("td");
let price = document.createElement("td");
id.textContent = this.id;
name.textContent = this.foodName;
type.textContent = this.foodType;
price.textContent = this.price;
row.appendChild(id);
row.appendChild(name);
row.appendChild(type);
row.appendChild(price);
fTable.appendChild(row);
};
getData();
function getData(){
let retrivedData = localStorage.getItem("stringifiedData");
let parsedData = JSON.parse(retrivedData);
if(parsedData!=null){
for (let i = 0; i < parsedData.length; i++) {
let newFoodOP = new food(
parsedData[i].foodName,
parsedData[i].foodType,
parsedData[i].price
);
}
}
for (let i = 0; i < allFood.length; i++) {
allFood[i].Render();
}
console.log(allFood);
}

How to save added data from HTML Table to SQL (PHPMYADMIN)

So here is my situation; I'm trying to save the data from the table which is added by filling up the form, I don't know how to save this to my database in phpmyadmin using javascript or ajax. A sample code is deeply appreciated. Thanks! PS: I'm a beginner, I'm just scraping the internet for code and trying to make do of what I get. Please Help :D
<html>
<body>
<div class = "inputfield">
<label>First Name:</label>
<input type="text" id="fname"><br>
<label>Last Name:</label>
<input type="text" id="lname"><br>
<label>Gender:</label>
<select name="gender" id="gender">
<option>Male</option>
<option>Female</option>
</select><br>
<label>HOURS:</label>
<input type="number" min=".5" max="12" step=".5" name="hours" id="hours" placeholder="--.5 to 12--"> <br>
</div>
<div class = "tablefield">
<table class="mtable" id="mtable">
<tr>
<th width="27%">First Name</th>
<th width="27%">Last Name</th>
<th width="15%">Gender</th>
<th width="15%">Hour</th>
<th width="16%">Edit</th>
</tr>
</table>
<table class="sumtable">
<tr><b>
<td class="sum">TOTAL HOURS</td>
<td class="sum1" id="sumtd"></td>
</b></tr>
</table>
</div>
<div class="buttons">
<button type = "button" onclick="add1('mtable')">ADD</button>
<button type = "reset" name="reset" class="btnclr">CLEAR</button>
<button type = "button" name="save" onclick="savefunc()">SAVE</button>
</div>
<input type = "hidden" name="hid1" id="hid1">
<input type = "hidden" name="hid2" id="hid2">
<input type = "hidden" name="hid3" id="hid3">
<input type = "hidden" name="hid4" id="hid4">
<script>
var sum = 0;
function add1(){
"use strict";
var hour1 = document.getElementById("hours").value;
sum = parseFloat(sum)+ parseFloat(hour1);
document.getElementById("sumtd").innerHTML = sum;
var table = document.getElementById("mtable"),rindex2;
var rowCount = table.rows.length;
var row = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var td4 = document.createElement('td');
var element1 = document.createElement("Button");
element1.type = "button";
element1.name = "btnedit";
element1.innerHTML = "Update";
element1.setAttribute('class','btnedit');
var element2 = document.createElement("Button");
element2.type = "button";
element2.name = "btndel";
element2.innerHTML = "Delete";
element2.setAttribute('class','btndel');
for(var i=0; i<rowCount; i++) {
element1.onclick = function () {
try {
rindex2 = this.parentNode.rowIndex;
sum = parseFloat(sum) - parseFloat(table.rows[rindex2].cells[3].innerHTML);
console.log(rindex2);
this.parentNode.cells[0].innerHTML = document.getElementById("fname").value;
this.parentNode.cells[1].innerHTML = document.getElementById("lname").value;
this.parentNode.cells[2].innerHTML = document.getElementById("gender").value;
this.parentNode.cells[3].innerHTML = document.getElementById("hours").value;
sum = parseFloat(sum) + parseFloat(document.getElementById("hours").value);
document.getElementById("sumtd").innerHTML = sum;
}catch(e){
alert(e);
}};
element2.onclick = function () {
try {
rindex2 = this.parentNode.rowIndex;
console.log(rindex2);
sum = parseFloat(sum) - parseFloat(table.rows[rindex2].cells[3].innerHTML);
document.getElementById("sumtd").innerHTML = sum;
table.deleteRow(rindex2);
}catch(e){
alert(e);
}};
}
td1.innerHTML = document.getElementById("fname").value;
td2.innerHTML = document.getElementById("lname").value;
td3.innerHTML = document.getElementById("gender").value;
td4.innerHTML = document.getElementById("hours").value;
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(element1);
row.appendChild(element2);
table.children[0].appendChild(row);
}
function savefunc(){
var table1 = document.getElementById("mtable");
var hid1 = document.getElementById("hid1").value;
var hid2 = document.getElementById("hid2").value;
var hid3 = document.getElementById("hid3").value;
var hid4 = document.getElementById("hid4").value;
for (var r = 1, n = table1.rows.length; r < n; r++){
var c0 = table1.rows[r].cells[0].innerHTML;
var c1 = table1.rows[r].cells[1].innerHTML;
var c2 = table1.rows[r].cells[2].innerHTML;
var c3 = table1.rows[r].cells[3].innerHTML;
var c4 = table1.rows[r].cells[4].innerHTML;
hid1 = c0;
hid2 = c1;
hid3 = c2;
hid4 = c3;
console.log(hid1);
console.log(hid2);
console.log(hid3);
console.log(hid4);
}
}
</script>
</body>
</html>
I've figure it out. i just include this on the bottom of my loop statement and added a save.php file. Use this as reference https://www.studentstutorial.com/ajax/insert-data
$.ajax({
url: "save.php",
type: "POST",
data: {
fname: hid1,
lname: hid2,
gender: hid3,
hour: hid4
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
alert("Save Successful!");
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});

Javascript Delete row with checkbox

Hi i'm a beginner and I'm trying to do a simple CRUD Car apps but i cannot delete row with my function deleteRow().
I've create a function call deleteRow i add a checkbox in every row with the createElement method and i'm setting the Id attribute using the setAttribute() method.In my function i'm trying to get to the checkbox to see if its checked and if so using the deleteRow method to delete the row.
function addRow() {
/* check if its empty */
var brandValue = document.getElementById("brand").value;
var modelValue = document.getElementById("model").value;
if (brandValue == "" || modelValue == "") {
return alert("Make sure you enter a brand and a model!")
}
/* Add a row */
"use strict";
var table = document.getElementById("table");
var row = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("INPUT");
td3.setAttribute("type", "checkbox");
td3.setAttribute("id", "cb");
td1.innerHTML = document.getElementById("brand").value;
td2.innerHTML = document.getElementById("model").value;
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
table.children[0].appendChild(row);
document.getElementById('brand').value = "";
document.getElementById('model').value = "";
}
var temp = 1;
function deleteRow() {
for (var j = temp - 2; j >= 0; j--) {
if (document.table.cb[j].checked) {
document.getElementById("table").deleteRow(j + 1);
}
}
}
<input type="text" id="brand" placeholder="Add a brand">
<input type="text" id="model" placeholder="Add a Model">
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
<table id="table">
<div class="tableDiv">
<tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
Right now nothing happen when i'm trying to delete and i have nothing in the browser console.
Thanks for your help.
Try this:
const $brand = document.getElementById("brand")
const $model = document.getElementById("model")
const $table = document.getElementById("table")
function addRow() {
/* check if its empty */
if ($brand.value == "" || $model.value == "") {
return alert("Make sure you enter a brand and a model!")
}
let $row = document.createElement("tr");
let $td1 = document.createElement("td");
let $td2 = document.createElement("td");
let $td3 = document.createElement("input");
$td3.setAttribute("type", "checkbox");
$td1.innerHTML = $brand.value;
$td2.innerHTML = $model.value;
$row.appendChild($td1);
$row.appendChild($td2);
$row.appendChild($td3);
$table.children[0].appendChild($row);
$brand.value = "";
$model.value = "";
}
function deleteRow() {
let checkboxs = $table.querySelectorAll("input[type='checkbox']:checked")
checkboxs.forEach(checkbox => checkbox.parentElement.remove())
}
<input type="text" id="brand" placeholder="Add a brand"></input>
<input type="text" id="model" placeholder="Add a Model"></input>
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
</div>
<table id="table">
<div class="tableDiv" <tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
for (var j = temp - 2; j >= 0; j--) { this loop never starts due to temp being 1.
1 - 2 = -1 so the loop condition (j >= 0) is never true.
Your main mistake is that you don't need to iterate anything, you can select the checked elements directly.
Try using document.querySelector("#table input[type='checkbox']:checked")
Another thing is that now you are assigning the same id to multiple elements. This should not be done, it can lead to unexpected behavior. Consider using class or custom attribute instead
let checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
checkboxes.forEach(checkbox => checkbox.parentElement.parentElement.remove());

Categories

Resources