Function needs double click to trigger - javascript

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>

Related

Delete table row with 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>

recreate auto increment php in javascript

i've been looking a while if somebody had a similar question, and there are a few, but not with the solution i need. their increments work perfectly fine but when they have a some rows like this
id
1 hello
2 hello
3 hello
4 hello
but when they delete row 3, row 4 becomes 3. I want it just like php where 4 stays 4 and doesn't become 3 so the next time you would add a row it would look like
id
1 hello
2 hello
4 hello
5 hello
see the following code for yourself; I can't figure it out
<table id="myTable">
<thead>
<tr>
<th>id</th>
<th>titel</th>
<th>beschrijving</th>
<th>deadline</th>
<th>delete task</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="forms flex flex-around">
<form >
<h2>Add Tasks</h2>
titel: <input type="text" name="titel" id="send"><br />
beschrijving: <input type="text" id="send" name="beschrijving"><br />
deadline: <input type="date" id="send" name="deadline"><br />
<!-- <input type="submit" value="Add" name="type" class="center" onclick="myFunction()"> -->
<button type="button" value="Add" id="handler" class="center button-add" onclick="addRow(); ">add task</button>
</form>
</div>
$(document).ready(function() {
buildTable();
});
function buildTable() {
const retrievedTaskObject = localStorage.getItem("table");
const parsedObject = JSON.parse(retrievedTaskObject);
for (i = 0; i < parsedObject.length; i++) {
addRow(parsedObject[i])
}
}
function addRow(rowData = false) {
var table = document.getElementById("myTable").getElementsByTagName('tbody')[0];
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
if (!rowData) {
cell2.innerHTML = '<td>' + document.querySelector('[name="titel"]').value; + '</td>';
cell3.innerHTML = document.querySelector('[name="beschrijving"]').value;
cell4.innerHTML = document.querySelector('[name="deadline"]').value;
} else {
cell2.innerHTML = '<td>' + rowData.title + '</td>';
cell3.innerHTML = rowData.description;
cell4.innerHTML = rowData.deadline;
}
cell5.innerHTML = '<button class="button-add last-row" type="button" onClick="deleteRow()" >' +
'delete</button>';
getAndSaveTableValues();
}
function getTblValues(tableName = false) {
if (!tableName) {
console.log('Please enter a tableName, function won\'t work without it');
return;
}
const dataArray = new Array();
$(`${tableName} tbody tr`).each(function(rowIndex, tr) {
dataArray[rowIndex] = {
"id": rowIndex,
"title": $(tr).find('td:eq(1)').text(),
"description": $(tr).find('td:eq(2)').text(),
"deadline": $(tr).find('td:eq(3)').text()
}
});
return dataArray;
}
function deleteRow() {
var td = event.target.parentNode;
var tr = td.parentNode;
tr.parentNode.removeChild(tr);
getAndSaveTableValues();
};
as you can see I have pretty much everything set, but because my messyness and few months of coding I completely lost track and don't know how to fix the increment I've tried many things but ended up breaking it fully,
Any help is welcome not only the solution but if you see something that could be smarter coded let me know
I do not fully know how to fix this problem, but have you tried to replace the value with null instaed of .removeChild(tr)?

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

How to add two functions into one, and execute based on parameter passed

Looking to make one button execute two different functions based on the parameters passed in. One function adds a new row to the table based on the filled out form values and the other functions saves the form values in a previously added row. As shown below, I want to add the add the functions
editHtmlTbleSelectedRow() and addHtmlTableRow() into one function and do one or the other based on the parameter passed.
Any help or tips on how to accomplish this would be appreciated, Here is the code:
HTML
<div class="container">
<div class="tab tab-1">
<table id="table" border="1">
<tr>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</tr>
</table>
</div>
<div class="tab tab-2">>
Name :<input type="text" name="name" id="name" required><p id="errorName" class="hide">*Name: All letters </p>
Email :<input type="email" name="email" id="email" required><p id="errorEmail" class="hide">*Email: blah#blah.com</p>
Age :<input type="number" name="age" id="age" required><p id="errorAge" class="hide">*Age: 3-100 </p>
<button type="button" id="add" class="btn btn-success">Add New</button>
<button type="button" id="edit add" class="btn btn-primary">Save</button>
<button type="button" id="remove" class="btn btn-danger">Remove</button>
</div>
</div>
Javascript
function addHtmlTableRow(){
// get the table by id
// create a new row and cells
// get value from input text
// set the values into row cell's
if(checkEmptyInput()){
resetBorder();
if(document.getElementById('email').value !== "" && document.getElementById('age').value !== "" && document.getElementById('name').value !== ""){
var editBtn = document.createElement('button');
var delBtn = document.createElement('button');
editBtn.innerHTML = 'Edit';
editBtn.id = 'editRow';
delBtn.innerHTML = 'Remove';
delBtn.id = 'removeRow';
var newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell5 = newRow.insertCell(3),
cell4 = newRow.insertCell(4),
name = document.getElementById("name").value,
email = document.getElementById("email").value,
age = document.getElementById("age").value;
cell1.innerHTML = name;
cell2.innerHTML = email;
cell3.innerHTML = age;
cell4.appendChild(delBtn);
cell5.appendChild(editBtn);
document.getElementById("name").value = '';
document.getElementById("email").value= '';
document.getElementById("age").value = '';
// call the function to set the event to the new row
selectedRowToInput();
}
}
}
// display selected row data into input text
function selectedRowToInput()
{
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
// get the seected row index
rIndex = this.rowIndex;
document.getElementById("name").value = this.cells[0].innerHTML;
document.getElementById("email").value = this.cells[1].innerHTML;
document.getElementById("age").value = this.cells[2].innerHTML;
};
}
}
selectedRowToInput();
function editHtmlTbleSelectedRow()
{
var name = document.getElementById("name").value,
email = document.getElementById("email").value,
age = document.getElementById("age").value;
console.log(name, email, age);
if(checkEmptyInput()){
table.rows[rIndex].cells[0].innerHTML = name;
table.rows[rIndex].cells[1].innerHTML = email;
table.rows[rIndex].cells[2].innerHTML = age;
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("age").value = "";
console.log(name, email, age);
resetBorder();
}
document.getElementById('add').addEventListener('click',
addHtmlTableRow);
document.getElementById('edit').addEventListener('click',
editHtmlTbleSelectedRow);
Thank you

How to make input text field dynamic expending with document.createElement("input") method?

This is my first question on this awesome community.
I am using this javascript code to build a dynamic table:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
element2.onkeypress = "this.style.width = ((this.value.length + 1) * 8) + 'px'";
cell2.appendChild(element2);
}
And following html code to print it:
<table id="dataTable" style="width: 300px;" border="0">
<tr>
<td ><input type="checkbox" name="chk" /></td>
<td <input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';"> </td>
</tr>
</table>
My problem is that- I want my text input field to be dynamically expending, but due to using 'document.createElement("input");' in the Javascript, only the first text input field expends dynamically rest
You can define your expanding function and reuse it later, like this:
expandTextBox = function (tb) {
tb.style.width = ((tb.value.length + 1) * 8) + 'px';
}
And when you create element:
var element2 = document.createElement("input");
element2.onkeypress = function() { expandTextBox(element2); };
And in html:
<input id="txt" type="text" onkeypress="expandTextBox(this)">
See the Fiddle
When add events to dynamically created elements in javascript, you must define the event code as a function not as a string!
So, modify your addRow function to this:
...
element2.onkeypress = function(){this.style.width = ((this.value.length+1)*8)+'px'};

Categories

Resources