Data inserted into a form disappears on form submit - javascript

I'm trying to insert data through the following JavaScript code. The data inserted, however, disappears from the table when I click Submit.
Here's my code:
let myform = document.querySelector("form");
let myFN = document.getElementById("fname");
let myLN = document.getElementById("lname");
let MyPar = document.querySelector("p");
let submit = document.getElementById("submit");
myform.addEventListener("submit", (e) => {
if (myFN.value === "" || myLN.value === "") {
e.preventDefault();
MyPar.textContent = 'you need to fill all';
}
});
myform.addEventListener("submit", function() {
document.getElementById("table").style.display = "block";
// trigger the table form page
let table = document.getElementById("table");
let row = table.insertRow(-1);
let fname1 = row.insertCell(0);
let lname1 = row.insertCell(1);
fname1.innerHTML = document.getElementById("fname").value;
lname1.innerHTML = document.getElementById("lname").value;
});
table {
display: none;
}
table,
td {
border: 1px solid black;
}
<form>
<div>
<label for="fname">First name: </label>
<input id="fname" type="text" />
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" type="text" />
</div>
<div>
<input id="submit" type="submit" />
</div>
</form>
<p></p>
<table id="table">
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</table>

First, you should remove the event listener that checks whether or not the input fields are blank. You instead can use required for the input tags in the HTML because it has a built-in form validation.
Then, all you need to do is remove the if statement around the e.preventDefault() so it is executed every time the button is clicked.
let myform = document.querySelector("form");
let myFN = document.getElementById("fname");
let myLN = document.getElementById("lname");
let MyPar = document.querySelector("p");
let submit = document.getElementById("submit");
myform.addEventListener("submit", (e) => {
e.preventDefault();
});
myform.addEventListener("submit", function() {
document.getElementById("table").style.display = "block";
// trigger the table form page
let table = document.getElementById("table");
let row = table.insertRow(-1);
let fname1 = row.insertCell(0);
let lname1 = row.insertCell(1);
fname1.innerHTML = document.getElementById("fname").value;
lname1.innerHTML = document.getElementById("lname").value;
});
table {
display: none;
}
table,
td {
border: 1px solid black;
}
<form>
<div>
<label for="fname">First name: </label>
<input id="fname" type="text" required />
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" type="text" required />
</div>
<div>
<button id="submit">Submit</button>
</div>
</form>
<table id="table">
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</table>

Related

How can i get multiple input values with javascript

I tried to code a student manager like below. But when i ran my code in web there seem something error that i dont understanding. I can't get input value from gender and language. When i check console to see something wrong in my code, just a blank.So i dont know why i can't get value when i didn't get any error from console. Because my english skill is not good so I can't explain my mistake. i'm sorry for that. Can someone help me. Thanks firstenter image description here
<table>
<form onsubmit="event.preventDefault();onFormSubmit();" autocomplete="off">
<div id="s1">
<label>Student Name:</label>
<input type="text" placeholder="Input student name"
title="Please fill out this field" id="name" name="name">
</div>
<div id="s2">
<label>Student DOB:</label>
<input type="date" placeholder="dd-mm-yyyy" id="date" name="date">
</div>
<div id="s3">
<label>Student gender:</label>
<input type="radio" id="gender1" class="gender" name="gender">Male
<input type="radio" id="gender2" class="gender" name="gender">Female
</div>
<div id="s4">
<label>Student Language</label>
<input type="checkbox" id="lang1" class="lang" name="lang">English
<input type="checkbox" id="lang2" class="lang" name="lang">Vietnamese
<input type="checkbox" id="lang3" class="lang" name="lang">Japanese
<input type="checkbox" id="lang4" class="lang" name="lang">Chinese
<input type="checkbox" id="lang5" class="lang" name="lang">French
</div>
<div id="s5">
<label>Student Class:</label>
<select id="class" name="class">
<option>C1608G</option>
</select>
Add class
</div>
<button id="bt">Add</button>
</form>
<br><br><br>
<h2><strong>Student List</strong></h2>
<br>
<table id="table" border="1">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>DOB</th>
<th>Gender</th>
<th>Language</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here is my javascript code
var selectedRow = null
function onFormSubmit() {
var formData = readFormData();
// check empty row
if (selectedRow == null) {
// Insert New User Record
insertNewRecord(formData);
}
else {
// Update New User Record
updateRecord(formData);
}
// Reset Input Values
resetForm();
}
function readFormData() {
var formData = {};
// Get Values From Input
formData["name"] = document.getElementById("name").value;
formData["class"] = document.getElementById("class").value;
formData["date"] = document.getElementById("date").value;
formData["gender"] = document.getElementsByClassName("gender").value;
formData["lang"] = document.getElementsByClassName("lang").value;
// return Form Data
return formData;
}
function insertNewRecord(data) {
var table = document.getElementById("table").getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.length);
cell1 = newRow.insertCell(0);
cell1.innerHTML = data.name;
cell2 = newRow.insertCell(1);
cell2.innerHTML = data.class;
cell3 = newRow.insertCell(2);
cell3.innerHTML = data.date;
cell4 = newRow.insertCell(3);
cell4.innerHTML = data.gender;
cell5 = newRow.insertCell(4);
cell5.innerHTML = data.lang;
cell5 = newRow.insertCell(5);
cell5.innerHTML = 'Delete';
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.date;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
function resetForm() {
document.getElementById("name").value = "";
document.getElementById("class").value = "";
document.getElementById("date").value = "";
document.getElementsByClassName("gender").value = "";
document.getElementsByClassName("lang").value = "";
selectedRow = null;
}
function onDelete(td) {
if (confirm('Are you sure to delete this record ?')) {
row = td.parentElement.parentElement;
document.getElementById("table").deleteRow(row.rowIndex);
resetForm();
}
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.data;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
Two major problems you have in your code.
Your radio/checkboxes need to have values - your code cannot infer the text next to them as the value (without some additional coding and anyways that's not the right way to do it)
To check which radio is selected, you can use querySelector and the ? flag. Here's what it looks like in your code after I've added it:
formData["gender"] = document.querySelector(".gender:checked")?.value || '';
Which is: document.querySelector(".gender:checked") finds the item with the class name 'gender' that is checked (the psuedo class :checked does that). If it doesn't exist (if there isn't an element with that class name or none of them are checked), the ? flag captures that and instead a blank value is used. (Otherwise it might throw an error or be undefined)
To get all the checked checkboxes, you can use this kind of structure:
formData["lang"] = [];
// creates the array
document.querySelectorAll(".lang:checked").forEach(item => formData["lang"].push(item.value));
// loops through each checked checkbox and gets it's value, adding it to the array
formData["lang"] = formData["lang"].join(', ')
// this converts your array into a list that is comma separated. This line is optional because javascript will show your array as a comma separated list anyways
var selectedRow = null
function onFormSubmit() {
var formData = readFormData();
// check empty row
if (selectedRow == null) {
// Insert New User Record
insertNewRecord(formData);
} else {
// Update New User Record
updateRecord(formData);
}
// Reset Input Values
resetForm();
}
function readFormData() {
var formData = {};
// Get Values From Input
formData["name"] = document.getElementById("name").value;
formData["class"] = document.getElementById("class").value;
formData["date"] = document.getElementById("date").value;
formData["gender"] = document.querySelector(".gender:checked")?.value || '';
formData["lang"] = [];
document.querySelectorAll(".lang:checked").forEach(item => formData["lang"].push(item.value));
formData["lang"] = formData["lang"].join(', ')
// return Form Data
return formData;
}
function insertNewRecord(data) {
var table = document.getElementById("table").getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.length);
cell1 = newRow.insertCell(0);
cell1.innerHTML = data.name;
cell2 = newRow.insertCell(1);
cell2.innerHTML = data.class;
cell3 = newRow.insertCell(2);
cell3.innerHTML = data.date;
cell4 = newRow.insertCell(3);
cell4.innerHTML = data.gender;
cell5 = newRow.insertCell(4);
cell5.innerHTML = data.lang;
cell5 = newRow.insertCell(5);
cell5.innerHTML = 'Delete';
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.date;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
function resetForm() {
document.getElementById("name").value = "";
document.getElementById("class").value = "";
document.getElementById("date").value = "";
document.getElementsByClassName("gender").value = "";
document.getElementsByClassName("lang").value = "";
selectedRow = null;
}
function onDelete(td) {
if (confirm('Are you sure to delete this record ?')) {
row = td.parentElement.parentElement;
document.getElementById("table").deleteRow(row.rowIndex);
resetForm();
}
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.data;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
<form onsubmit="event.preventDefault();onFormSubmit();" autocomplete="off">
<div id="s1">
<label>Student Name:</label>
<input type="text" placeholder="Input student name" title="Please fill out this field" id="name" name="name">
</div>
<div id="s2">
<label>Student DOB:</label>
<input type="date" placeholder="dd-mm-yyyy" id="date" name="date">
</div>
<div id="s3">
<label>Student gender:</label>
<input type="radio" id="gender1" class="gender" name="gender" value="Male">Male
<input type="radio" id="gender2" class="gender" name="gender" value="Female">Female
</div>
<div id="s4">
<label>Student Language</label>
<input type="checkbox" id="lang1" class="lang" name="lang" value="English">English
<input type="checkbox" id="lang2" class="lang" name="lang" value="Vietnamese">Vietnamese
<input type="checkbox" id="lang3" class="lang" name="lang" value="Japanese">Japanese
<input type="checkbox" id="lang4" class="lang" name="lang" value="Chinese">Chinese
<input type="checkbox" id="lang5" class="lang" name="lang" value="French">French
</div>
<div id="s5">
<label>Student Class:</label>
<select id="class" name="class">
<option>C1608G</option>
</select>
Add class
</div>
<button id="bt">Add</button>
</form>
<br><br><br>
<h2><strong>Student List</strong></h2>
<br>
<table id="table" border="1">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>DOB</th>
<th>Gender</th>
<th>Language</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

How to display radio and checkbox values in table using javascript?

When I click display button it displays name and age but gender and checkbox is incorrect it displays first value only. I want to display which i select.
radio data and checkbox data should display.
(function setup() {
"use strict";
var NameElem = document.getElementById("name");
var genderElem = document.getElementById("gender");
var ageElem = document.getElementById("age");
var languageElem = document.getElementById("language");
var tableElem = document.getElementById("table");
document.getElementById("display").addEventListener("click", function() {
var newRow = tableElem.insertRow(-1);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(NameElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(1);
newText = document.createTextNode(genderElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(2);
newText = document.createTextNode(ageElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(3);
newText = document.createTextNode(languageElem.value);
[newCell.appendChild][1](newText);
NameElem.value = "";
genderElem.value = "";
ageElem.value = "";
languageElem.value = "";
tableElem.value = "";
});
})();
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="container">
<br>
<br>
<h3 class="text-center">Display answers of form fill in inside a table</h3>
<br>
<br>
<form>
<div class="form-group">
<label>First Name</label>
<input id="name" class="form-control form-control-sm" />
</div>
<div class="form-group">
<label>Age</label>
<input id="age" class="form-control form-control-sm" />
</div>
<div class="form-group">
Gender:<input type="radio" name="male" id="gender" value="male">Male
<input type="radio" name="female" id="gender" value="female">
<label for="female">Female</label>
</div>
<div class="form-group">
<label>Language</label>
<input type="checkbox" id="language" name="malayalam" value="Malayalam">Malayalam
<input type="checkbox" id="language" name="english" value="English">English
<input type="checkbox" id="language" name="hindi" value="Hindi">Hindi
</div>
<button type="button" id="display" class="btn btn-sm btn-primary">Display</button>
</form>
<br>
<br>
<table class="table border" id="table">
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Language</th>
</tr>
</table>
<script type="text/javascript" src="form.js"></script>
</div>
Well, the code does exactly what you asked for.
var genderElem = document.getElementById("gender");
// returns the element with ID "gender"
You are mixing name attribute with ID.
An ID must always be unique : a web page can't contain several elements with the same ID.
What you are looking for is the checked input of name "gender".
var genderValue = '';
document.querySelectorAll('input[name=gender]').forEach((e)=>{
if (e.checked==true) { genderValue = e.value; }
});
Couple of mistakes you did:
Radio buttons and Checkboxes should always have same name if they are in the same group.
Always keep ID different, its bad practice to keep ID same for multiple elements.
When you are trying to get the value of Radio button or Checkboxes, fetch it using getElementsByName and run a loop over all on click of display button not outside.
Safer side and to reduce the LOC, give your form an ID and reset the form on submit using formId.reset() method. (in your code I have given form an id myForm so I have added myForm.reset(); at the end of the code on submit method)
See the Snippet below:
(function setup() {
"use strict";
var myForm = document.getElementById("myForm");
var NameElem = document.getElementById("name");
var ageElem = document.getElementById("age");
var genderElem = document.getElementsByName('gender');
var languageElem = document.getElementsByName("language");
var tableElem = document.getElementById("table");
var selectedGender = '';
var selectedLanguages = [];
document.addEventListener("click", function(event){
if(event.target.classList.contains("delete")){
var row = event.target.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
document.getElementById("display").addEventListener("click", function() {
for(var i = 0; i < genderElem.length; i++) {
if(genderElem[i].checked)
selectedGender = genderElem[i].value;
}
for(var i = 0; i < languageElem.length; i++) {
if(languageElem[i].checked)
selectedLanguages.push(languageElem[i].value);
}
var newRow = tableElem.insertRow(-1);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(NameElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(1);
newText = document.createTextNode(selectedGender);
newCell.appendChild(newText);
newCell = newRow.insertCell(2);
newText = document.createTextNode(ageElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(3);
newText = document.createTextNode(selectedLanguages.toString());
newCell.appendChild(newText);
newCell = newRow.insertCell(4);
var deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.classList.add("delete");
newCell.appendChild(deleteBtn);
/*NameElem.value = "";
genderElem.value = "";
ageElem.value = "";
languageElem.value = "";
tableElem.value = "";*/
myForm.reset();
selectedGender = "";
selectedLanguages = [];
});
})();
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="container">
<br>
<br>
<h3 class="text-center">Display answers of form fill in inside a table</h3>
<br>
<br>
<form id="myForm">
<div class="form-group">
<label>First Name</label>
<input id="name" class="form-control form-control-sm" />
</div>
<div class="form-group">
<label>Age</label>
<input id="age" class="form-control form-control-sm" />
</div>
<div class="form-group">
Gender:<input type="radio" name="gender" id="male" value="Male">
<label for="male">Male</label>
<input type="radio" name="gender" id="female" value="Female">
<label for="female">Female</label>
</div>
<div class="form-group">
<label>Language</label>
<input type="checkbox" id="malayalam" name="language" value="Malayalam">Malayalam
<input type="checkbox" id="english" name="language" value="English">English
<input type="checkbox" id="hindi" name="language" value="Hindi">Hindi
</div>
<button type="button" id="display" class="btn btn-sm btn-primary">Display</button>
</form>
<br>
<br>
<table class="table border" id="table">
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Language</th>
<th>Action</th>
</tr>
</table>
<script type="text/javascript" src="form.js"></script>
</div>
UPDATE 1 : Added delete row feature
document.addEventListener("click", function(event){
if(event.target.classList.contains("delete")){
var row = event.target.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
newCell = newRow.insertCell(4);
var deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.classList.add("delete");
newCell.appendChild(deleteBtn);

Change element between cells of a table

I'm creating a table with two fields, and I'm trying to do:
When I register an user, the username will be displayed, with this username when I click a button, the cell field will be filled with the username and the button will be hidden (ok until now).
When I click on the button of the second cell, this data will be passed to that cell and the past cell will be reset to the first name.
This second part I'm trying but seems impossible, what I can do for solve this?
<script>
var list = document.getElementById('users');
function addUser(){
var username = document.getElementById('username').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username));
list.appendChild(entry);
return false;
}
var hidden = false;
function teste(){
hidden = !hidden;
if(hidden) {
document.getElementById('testebut').style.visibility = 'hidden';
var coe = document.getElementById('username').value;
document.getElementById('lbl1').innerHTML = "user: " + coe;
} else {
document.getElementById('testebut2').style.visibility = 'visible';
}
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<html>
<head>
</head>
<body>
<fieldset>
<form id="myform" onsubmit="return addUser()">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name"/>
<input id="email" type="email" name="email" placeholder="email"/>
<button type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
</fieldset>
<table>
<tr>
<th>User</th>
<th>User</th>
</tr>
<tr>
<td id="lbl1">---<button id="testebut" onClick="teste();">X</button></td>
<td id="lbl2">---<button id="testebut2">X</button></td>
</tr>
</table>
</body>
</html>
I have made several changes to your code to achieve what in my opinion is you needed. Instead of events in HTML I created some event listeners using JavaScript. I hope this is of help to you.
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<fieldset>
<form id="myform" >
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name"/>
<input id="email" type="email" name="email" placeholder="email"/>
<button type="submit" id="addUserBtn">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
</fieldset>
<table>
<tr>
<th>User</th>
<th>User</th>
</tr>
<tr>
<td>
<span id="lbl1">---</span>
<button id="testebut">X</button>
</td>
<td>
<span id="lbl2">---</span>
<button id="testebut2">X</button>
</td>
</tr>
</table>
</body>
</html>
<script>
var list = document.getElementById('users');
if ( document.getElementById( "addUserBtn" ) ) {
document.getElementById( "addUserBtn" ).addEventListener( "click", function( e ) {
//prevent the page from reloading and add the user to the list
e.preventDefault();
addUser();
});
}
function addUser(){
var username = document.getElementById('username').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username));
list.appendChild(entry);
}
//get all the teste buttons
let testeButtons = document.querySelectorAll( "button[id^='testebut']" );
//add event listener to all the teste buttons
for ( let i = 0; i < testeButtons.length; i++ ) {
testeButtons[ i ].addEventListener( "click", function( e ) {
teste( e.target.id );
});
}
function teste( id ){
let resetField = "---";
//this will only get the last username in the list
let userName = document.getElementById('username').value;
//check if clicked button is testebut and that it's not hidden
//then add the user name to the field and reset the other field
if ( id === "testebut" ) {
document.getElementById( "lbl1" ).innerHTML = "user: " + userName;
document.getElementById( "lbl2" ).innerHTML = resetField;
} else if ( id === "testebut2" ) {
document.getElementById( "lbl2" ).innerHTML = "user: " + userName;
document.getElementById( "lbl1" ).innerHTML = resetField;
}
}
</script>

how to edit all the td's on tbody

so what im trying to do is to add the "change" functionality in my code, it works for only the first td but not any other, when i click the other td it automaticly edits the first one.
does anyone know why my code is only changing the td>name/td> and not the td>adress/td> or any other td>
html:
<form id="registrering">
<label>Navn: <input id="inpnavn" placeholder="Raahim Khan" type="text" required></label>
<label>Adresse: <input id="inpadresse" type="text" placeholder="Adresse 12" required></label>
<label>Mobilnummer: <input id="inpmobilnummer" placeholder="12345678" required></select></label>
<label>Kjønn:
<select id="inpkjønn" required>
<option value="" selected disabled hidden>Velg kjønn</option>
<option>Mann</option>
<option>Kvinne</option>
<option>intetkjønn</option>
</select>
</label>
<button type="submit">Send inn</button>
</form>
//showing the data on website
function hentruss(snapshot){
var pk = snapshot.key;
var nyruss = snapshot.val();
var russref = database.ref("russ/" + nyruss.russ);
russref.on("value", function(snapshotruss){
var russobj = snapshotruss.val();
txttabell.innerHTML += `
<tr id="${pk}">
<td><label class="russlabel" onclick="edit('${pk}')">${nyruss.navn}</label><input type="text" class="editItem" style="display:none"></td>
<td><label class="russlabel" onclick="edit('${pk}')">${nyruss.adresse}</label><input type="text" class="editItem" style="display:none"></td>
<td>${nyruss.mobilnummer}</td>
<td>${nyruss.kjønn}</td>
<td><label class="delete" onclick="slett('${pk}')"><button>Slett</button></label></td>
</tr>
`;
});
}
//update the name,adress etc by clicking the element.
function edit(pk) {
var russen = russ.child(pk);
var label = document.querySelector(`#${pk} .russlabel`);
label.style.display = "none";
var tekst = label.innerText;
var inputfelt = document.querySelector(`#${pk} .editItem`);
inputfelt.style.display = "block";
inputfelt.value = tekst;
inputfelt.focus();
inputfelt.onblur = function() {
inputfelt.style.display = "none";
label.style.display = "block";
};
inputfelt.onchange = function() {
russen.update( {tekst: inputfelt.value} )
inputfelt.style.display = "none";
label.style.display = "block";
label.innerText = inputfelt.value;
};
}
It's a little hard to give an exact solution as the code snippets you have shared have a lot of calls to function whose context is not clear.. I have done my best to illustrate how you can do what you are trying to.. Maybe this will help get started in the right direction:
function handleSubmit(form) {
// Simulate creation of item using a form
var name = form.name.value;
var mobile = form.mobile.value;
// Generate random pk for demonstration
var pk = `pk${+new Date()}`;
var tableBody = document.querySelector('table tbody');
tableBody.innerHTML += ` <tr>
<td>
<label class="russlabel" onclick="edit(this)" data-pk="1" data-field="name">${name}</label>
<input class="editItem" style="display:none;" />
</td>
<td>
<label class="russlabel" onclick="edit(this)" data-pk="1" data-field="mobile">${mobile}</label>
<input class="editItem" style="display:none;" />
</td>
</tr>`;
return false;
}
function edit(label) {
var pk = label.dataset.pk;
var field = label.dataset.field;
var input = label.parentElement.children[1]; // Use label.parent.querySelector('input') if DOM is more complex
label.style = 'display:none;';
input.style = 'disply:block;';
input.focus();
input.value = label.innerHTML;
input.onchange = function() {
// pk and field are available here
// to Update DB state?? not sure how this code works
//var russen = russ.child(pk);
//russen.update( {tekst: inputfelt.value} )
}
input.onblur = function() {
label.innerHTML = input.value;
label.style = 'display:block;';
input.style = 'display:none;';
}
}
td {
padding: 0.5rem 0;
border-bottom: 1px solid black;
}
form {
margin: 1rem auto;
}
<form id="entry" onsubmit="return handleSubmit(this);">
<input name="name" placeholder="Name" />
<input name="mobile" placeholder="mobile" />
<input type="submit" value="Add Entry" />
</form>
<table>
<thead>
<tr>
<th>Name</th>
<th>Mobile</th>
</thead>
<tbody>
<tr>
<td>
<label class="russlabel" onclick="edit(this)" data-pk="1" data-field="name">Tom</label>
<input class="editItem" style="display:none;" />
</td>
<td>
<label class="russlabel" onclick="edit(this)" data-pk="1" data-field="mobile">1234</label>
<input class="editItem" style="display:none;" />
</td>
</tr>
</tbody>
</table>
Some notes:
It may be a good idea to read up on/ brush up on JS Events Here and refactor out the in line event handlers - these make your code hard to maintain, read, reason about, debug and are generally a bad idea.
Same goes for inline styles - avoid them. Try using classes with supporting styles in a stylesheet instead. (For example, on clicking a label, we could add an active class to the td element which in turn automatically hides the label and shows the input.
It's bad practice to reassign listeners to the inputs each time the label is clicked. The same functionality can be handled in a simpler and more graceful manner by using something like Event Delegation

Form submit without redirection and reloading

I am new to HTML. I have written an app, which allows user to add data and it's a local application. I have used forms int this application and I am facing a problem when form submission happens. I don't want the page to navigate/redirect and even don't want the same page to reload. Currently it's reloading the page. Please let me know what stops redirecting/reloading this app. I don't want any php code, application needs to be pure HTML and JS only.
Below is the HTML app code.
function addInfo() {
var InfoForm = document.forms["InfoForm"];
var trelem = document.createElement("tr");
for (var i = 0; i < InfoForm.length - 1; i++) {
var tdelem = document.createElement("td");
tdelem.innerHTML = InfoForm[i].value;
trelem.appendChild(tdelem);
}
document.getElementById("current_table").appendChild(trelem);
return false;
}
function done(e) {
e.preventDefault();
return false;
}
<div id="current_div">
<h2>Table Heading</h2>
<table border="1" id="current_table">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</table>
</div>
<div id="input_div">
<form name="InfoForm" accept-charset="utf-8" onsubmit="done(e)">
Name :
<input type="text" name="Name" value="">
<br>
<br>Age :
<input type="number" name="Age" value="">
<br>
<br>
<input type="submit" value="Add_Info" onclick="addInfo()">
</form>
</div>
This is not the right case to use a <form>. A <form> is used when you send via GET or POST method data to the server.
Therefore just use a <button> and two <input>.
It's easier to insert a row with insertRow and insertCell.
Complete example :
var nName = document.getElementById("nName");
var nAge = document.getElementById("nAge");
var btn = document.getElementById("addData");
var tbl = document.getElementById("myData");
function addData() {
var row = tbl.insertRow(0);
var d1 = row.insertCell(0);
var d2 = row.insertCell(1);
d1.innerHTML = nName.value;
d2.innerHTML = nAge.value;
}
btn.addEventListener("click", addData);
table {
margin: 15px 0;
}
#inputData > div {
margin: 5px 0;
}
#inputData > div > span {
display: inline-block;
width: 100px;
}
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody id="myData"></tbody>
<!-- Insert data -->
</table>
<div id="inputData">
<div><span>Name:</span>
<input type="text" id="nName">
</div>
<div><span>Age:</span>
<input type="number" id="nAge">
</div>
<div>
<button id="addData">Add data</button>
</div>
</div>
A form submission made a GET/POST request to the server. You can't use only JS for get data from a form submission.
If you don't want use server side language for some simple applications you can make your own function without really submit your form.
Example without form
function gocalc()
{
var number = document.getElementById("number").value;
var text = document.getElementById("text").value;
if(number>0 && number <11 && text !="")
{
for(var i=0;i<number;i++)
{
document.getElementById("content").innerHTML=document.getElementById("content").innerHTML+"<p>"+text+"</p>";
}
}
else
alert("You must write some text and choose a number between 1 and 10");
}
Choose a number between 1 and 10 <input type="number" max="10" id="number"> <br>
Write some text <input type="text" id="text"><br>
<button onclick="gocalc()">Ok</button>
<div id="content"></div>
You can use onsubmit attribute and call your function. don't forget to return false for prevent the form submission.
Example with form
function myfunction(myform)
{
alert(myform.mytext.value);
return false;
}
<form onsubmit="return myfunction(this)">
<input name="mytext" type="text">
<button type="submit">Submit</button>
</form>

Categories