Input to table in javascript - javascript

How can i add a content to html table with input fields.
For example here is html code:
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.getElementById("output");
output.innerHTML = "<tr><td>"+name+"</td><td>"+surname+"</td></tr>"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
<title>Document</title>
<style>
table,td{
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="">
<div>
<label for="name">Name</label>
<input type="text" id="name">
</div>
<div>
<label for="name">Surname</label>
<input type="text" id="surname">
</div>
</form>
<input type="button" onclick="add();" value="Add">
<div>
<table id="output">
<thead><td>Name</td><td>Surname</td></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
I want to output my input fields in the table like rows.. but it does not work i dont know where is my problem i get [object HTMLInputElement].
And how can i make it work for entering more values because like this i can only enter one row

How about using this code?
It adds surname and name below the thead.
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.querySelector("#output tbody");
output.innerHTML += "<tr><td>"+name.value+"</td><td>"+surname.value+"</td></tr>"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
<title>Document</title>
<style>
table,td{
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="">
<div>
<label for="name">Name</label>
<input type="text" id="name">
</div>
<div>
<label for="name">Surname</label>
<input type="text" id="surname">
</div>
</form>
<input type="button" onclick="add();" value="Add">
<div>
<table id="output">
<thead><td>Name</td><td>Surname</td></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>

you should assign the value of the input fields like below.
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.getElementById("output");
output.innerHTML = "<tr><td>"+name.value+"</td><td>"+surname.value+"</td></tr>"
}

Try:
Give tbody an id to avoid removing thead
<tbody id="output2"></tbody>
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.getElementById("output2");
output.innerHTML = "<tr><td>" + name.value + "</td><td>" + surname.value + "</td></tr>";
}
You are trying to insert an HTML input element instead of the value of the element.
To make multiple entries possible try the last line of the function to:
output.innerHTML += "<tr><td>" + name.value + "</td><td>" + surname.value + "</td></tr>";

Related

Add element to an Object (not array) in JS

I'm new to JS and I'm just practicing. I have this form that sets data in an object which is later displayed on the DOM. It works but it just shows a "key" at a time. If I add new elements they replace the existing one.
class Items {
constructor(namee, surnamee) {
this.namee = namee;
this.surnamee = surnamee;
}
}
function Func() {
event.preventDefault();
var nameval = document.getElementById('namee').value;
var surnval = document.getElementById('surnamee').value;
let newIt = new Items(nameval, surnval);
console.log(newIt)
document.getElementById('box').innerHTML = newIt.namee + " " + newIt.surnamee
}
<form onsubmit={Func()}>
<input id="namee" > </input>
<input id="surnamee"> </input>
<button type=submit> send </button>
</form>
<p id="box"> </p>
I've tried the push() method but it works with arrays. I've also tried to create an object instead of a class but I get the same grief
Thank you in advance
Maybe you looking for this:
class Items {
constructor(namee, surnamee) {
this.namee = namee;
this.surnamee = surnamee;
}
}
function Func() {
event.preventDefault();
var nameval = document.getElementById('namee').value;
var surnval = document.getElementById('surnamee').value;
let newIt = new Items(nameval, surnval);
console.log(newIt)
document.getElementById('box').innerHTML += `<p>` + newIt.namee + " " + newIt.surnamee + `</p>`;
}
<form onsubmit={Func()}>
<input id="namee" > </input>
<input id="surnamee"> </input>
<button type=submit> send </button>
</form>
<p id="box"> </p>
class Items {
constructor(namee, surnamee) {
this.namee = namee;
this.surnamee = surnamee;
}
}
function Func() {
event.preventDefault();
var nameval = document.getElementById('namee').value;
var surnval = document.getElementById('surnamee').value;
let newIt = new Items(nameval, surnval);
let html = `${document.getElementById('box').innerHTML}<p>${newIt.namee} ${newIt.surnamee}</p>`
document.getElementById('box').innerHTML = html
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<form onsubmit={Func()}>
<input id="namee" > </input>
<input id="surnamee"> </input>
<button type=submit> send </button>
</form>
<p id="box"> </p>
</body>
</html>
Hope it help :)
or you can use this
https://www.w3schools.com/jsref/met_node_appendchild.asp
any stored value can be wrapped in a div tag
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<form onsubmit={Func()}>
<input id="namee" > </input>
<input id="surnamee"> </input>
<button type=submit> send </button>
</form>
<p id="box"> </p>
</body>
</html>
<script>
class Items {
constructor(namee, surnamee) {
this.namee = namee;
this.surnamee = surnamee;
}
}
function Func() {
event.preventDefault();
var nameval = document.getElementById('namee').value;
var surnval = document.getElementById('surnamee').value;
let newIt = new Items(nameval, surnval);
console.log(newIt)
const row = document.createElement('div');
row.innerText = newIt.namee + " " + newIt.surnamee;
document.getElementById('box').appendChild(row);
}
</script>

How to remove specific row in table using js

I am learning javascript and i made this simple page where you add your title and author. By clicking on add button the input is entered to table where you have remove button.
How can i implement a function remove(){} in javascript that removed the row of the table from where it was called, because i tried using output.lastElement.remove(); but that only removes the last row not the row from where the button is clicked. If you know how can i make this please give me an answer ty :).
var title = document.getElementById("title");
var author = document.getElementById("author");
var output = document.getElementById("output");
function addToTable(){
output.innerHTML += "<tr>" + "<td>" + title.value + "</td>" +
"<td>" + author.value + "</td>" +
"<td>" + "<input type='button' onclick='remove();' id='remove'value ='Remove'>"+ "</td>" + "</tr>"
}
function remove(){
}
label{
width: 100px;
display: inline-block;
}
table,th,td,tr,td{
border: 1px solid black;
border-collapse: collapse;
}
table td{
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable();">
</div>
<div>
<table id="output">
<th style="width:45%;">Title</th>
<th style="width:45%;">Author</th>
<th style="width:10%;">Button</th>
</table>
</div>
</body>
</html>
Just throw this to remove function as parametr and then call removeChild on parent.
var title = document.getElementById("title");
var author = document.getElementById("author");
var output = document.getElementById("output");
function addToTable(){
output.innerHTML += "<tr>" + "<td>" + title.value + "</td>" +
"<td>" + author.value + "</td>" +
"<td>" + "<input type='button' onclick='remove(this);' id='remove'value ='Remove'>"+ "</td>" + "</tr>"
}
function remove(btn){
var row = btn.parentNode;
row.parentNode.removeChild(row);
}
label{
width: 100px;
display: inline-block;
}
table,th,td,tr,td{
border: 1px solid black;
border-collapse: collapse;
}
table td{
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable();">
</div>
<div>
<table id="output">
<th style="width:45%;">Title</th>
<th style="width:45%;">Author</th>
<th style="width:10%;">Button</th>
</table>
</div>
</body>
</html>
Using modern javascript syntax:
const title = document.getElementById("title");
const author = document.getElementById("author");
const output = document.getElementById("output");
const addToTable = () => {
const dataId = `table-row-${new Date().getTime()}`;
output.innerHTML += `
<tr data-row-id="${dataId}">
<td>${title.value}</td>
<td>${author.value}</td>
<td>
<input type="button" onclick="remove('${dataId}')" value="Remove">
</td>
</tr>`;
}
const remove = (dataRowID) => {
output.querySelector(`[data-row-id="${dataRowID}"]`).remove();
}
label{
width: 100px;
display: inline-block;
}
table, th, td, tr, td {
border: 1px solid black;
border-collapse: collapse;
}
table td{
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable();">
</div>
<div>
<table id="output">
<th style="width:45%;">Title</th>
<th style="width:45%;">Author</th>
<th style="width:10%;">Button</th>
</table>
</div>
</body>
</html>
I advise you not to completely use old javascript syntax.
An example using event delegation.
function addToTable() {
const title = document.getElementById("title");
const author = document.getElementById("author");
const output = document.getElementById("output");
output.innerHTML +=
"<tr>" +
"<td>" +
title.value +
"</td>" +
"<td>" +
author.value +
"</td>" +
"<td>" +
"<button type='button'>remove</button>" +
"</td>" +
"</tr>";
}
function removeRow(e) {
if (e.target.tagName === "BUTTON") {
e.target.closest("tr").remove();
}
}
document.querySelector("#output").addEventListener("click", removeRow);
label{
width: 100px;
display: inline-block;
}
table,th,td,tr,td{
border: 1px solid black;
border-collapse: collapse;
}
table td{
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable();">
</div>
<div>
<table id="output">
<th style="width:45%;">Title</th>
<th style="width:45%;">Author</th>
<th style="width:10%;">Button</th>
</table>
</div>
</body>
</html>

how to iterate through HTML elements and sum the values using for loop

i have an issue using for loop to sum the values through elements inside HTML by pressing button but the code did not work correctly also i tried to show alert a massage that says "not a number" but every time show the same massage once i press the button
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input class="inp" type="" placeholder="Enter a Number " >
<input class="inp" type="" placeholder="Enter elec" >
<input class="inp" type="" placeholder="Enter food " >
<input class="inp" type="" placeholder="Enter car " >
<input class="inp" type="" placeholder="Enter resturent " >
<h1 class="total">total</h1>
<button class="btn">calculate</button>
<script
const btn= document.querySelector('.btn')
const total = document.querySelector('.total')
const inp = document.querySelectorAll('.inp')
btn.addEventListener('click',function(){
if (isNaN(inp.value)) {
alert("Not a number")
console.log(inp.value);
} if (inp.value === ""){
alert("enter number ")
}
for (let i = 0; i <inp.length; i++) {
let index = 0
const current = index + inp[i].value
total.innerHTML = index
}
})
</script>
</body>
</html>
Change to input type=number. Also check with typeof if the variable is a number. If not, you can convert it with JavaScript function parseInt().
Please change the type of your inputs, then move your "validation" inside your loop, then
move your counter outside the loop and change it to "let", then cast to number the input value before sum into the current.
have a nice day
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input class="inp" type="number" placeholder="Enter a Number ">
<input class="inp" type="number" placeholder="Enter elec">
<input class="inp" type="number" placeholder="Enter food ">
<input class="inp" type="number" placeholder="Enter car ">
<input class="inp" type="number" placeholder="Enter resturent ">
<h1 class="total">total</h1>
<button class="btn">calculate</button>
<script>
let btn = document.querySelector('.btn')
btn.addEventListener('click', function () {
const total = document.querySelector('.total')
const inps = document.querySelectorAll('.inp')
let current = 0;
for (let i = 0; i < inps.length; i++) {
if (isNaN(inps[i].value)) {
alert("Not a number")
break;
} if (inps[i].value == "") {
alert("enter number ")
break;
}
current += +inps[i].value
total.innerHTML = current
}
})
</script>
</body>
</html>

I want to return 'Alert' box if someone submits empty form

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<input onclick="serve(); return false" type="submit">
</form>
<ol id="add"></ol>
</body>
<script>
function serve(){
const neww = document.getElementById('add');
let text = document.getElementById('todotext').value;
const a = document.createElement('li');
a.innerText = text;
neww.appendChild(a);
document.getElementById('todotext').value = "";
}
</script>
</html>
Here is my code and I want to return an 'Alert' if someone submit empty form.
How should I do it ? Any help will be appreciated
Here's an image:
Is this what you want?
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<button onclick="todotext.value != '' ? serve() : alert('Input field is blank')" >Submit</button>
</form>
<ol id="add"></ol>
</body>
<script>
var todotext = document.getElementById('todotext');
function serve() {
const neww = document.getElementById('add');
let text = todotext.value;
const a = document.createElement('li');
a.innerText = text;
neww.appendChild(a);
document.getElementById('todotext').value = "";
}
</script>
</html>
String.prototype.isEmpty = function() {
return (this.length === 0 || !this.trim());
};
function serve(){
const neww = document.getElementById('add')
let text = document.getElementById('todotext').value;
if( text.isEmpty() ){
alert('cannot be blank');
return;
}
const a = document.createElement('li')
a.innerText = text
neww.appendChild(a)
document.getElementById('todotext').value = ""
}
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<input onclick="serve(); return false" type="submit">
</form>
<ol id="add"></ol>
add condition when append new element by checking the value of todoText
function serve(){
const neww = document.getElementById('add')
let text = document.getElementById('todotext').value
if(text == ""){
alert('field is required');
}
else{
const a = document.createElement('li')
a.innerText = text
neww.appendChild(a)
document.getElementById('todotext').value = ""
};
}
function serve(){
const neww = document.getElementById('add')
let text = document.getElementById('todotext').value
if(text.trim().length === 0){
alert("Field is empty");
}else{
const a = document.createElement('li')
a.innerText = text
neww.appendChild(a)
document.getElementById('todotext').value = ""
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<input onclick="serve(); return false" type="submit">
</form>
<ol id="add"></ol>
</body>
</html>

Display JavaScript Object at the Bottom of HTML Form

I have an HTML Form that a user needs to fill out. It is information about a Student (Name, Email, Grade, Math, English, Social Studies). What I am trying to do is when the user fills out the Form and clicks the Submit button. It creates a JavaScript Object and adds it into another JS Object. I want the information input in the Form to display at the bottom of the webpage. I am purposely not using a database. I just want the information to exist while the page is up.
This is the HTML Form:
<!DOCTYPE html>
<html lang="en">
<head>
<!--Required Meta Tag-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<style>
.center {
text-align: center;
border: 3px solid green;
}
body {
font-family: Arial;
margin: 0;
}
/* Header/Logo Title */
.header {
padding: 10px;
text-align: center;
background: #1abc9c;
color: white;
font-size: 20px;
}
</style>
<title>Student Report Card</title>
</head>
<body>
<div class="header">
<br>
<h2>Student & Grade Input Form</h2>
<br>
</div>
<br>
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<input type="text" placeholder="Enter name" name="name" id="name" required><br>
<br>
<input type="email" placeholder="Enter Email" name="email" id="email" required><br>
<br>
<input type="number" placeholder="Enter Math Grade" name="math" id="math" required><br>
<br>
<input type="number" placeholder="Enter English Grade" name="eng" id="eng" required><br>
<br>
<input type="number" placeholder="Enter Math Grade" name="math" id="math" required><br>
<br>
<input type="number" placeholder="Enter Social Studies Grade" name="sstd" id="sstd" required><br>
<br>
<button type="submit" id="btn1">Submit</button>
<ul id="myList">
</ul>
</div>
<script src="scripts.js"></script>
</body>
</html>
This is the Javascript Code:
document.getElementById("btn1").addEventListener("click", inputFunc)
var studentList = new Object()
function inputFunc(){
var fname = document.getElementById("name").value
var email = document.getElementById("email").value
var math = document.getElementById("math").value
var eng = document.getElementById("eng").value
var sstd = document.getElementById("sstd").value
var x = Math.floor((Math.random() * 100) + 1);
var y = x.toString();
studentID = "student".concat(y)
var studentID = new Object();
studentID.name = fname
studentID.email = email
studentID.math = math
studentID.eng = eng
studentID.sstd = sstd
studentList[studentID] = studentID
console.log(studentList)
var obj = JSON.parse(JSON.stringify(studentList))
var information = document.getElementById("demo").innerHTML = obj.fname + ", " + obj.email + ", " + obj.math;
var node = document.createElement("LI");
var textnode = document.createTextNode(information);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
I am using the Random() method in JavaScript to create a random number that I am concatenating to the the "student" so it give it a unique ID. This is working correctly. I just can't display the information at the bottom of the page.
The Goal is after the user inputs information in the form it will display the content of the object below like so:
- Name, Email, Grade, English, Math, Social Studies
- Name, Email, Grade, English, Math, Social Studies
- Name, Email, Grade, English, Math, Social Studies
I have been able to solve this. I was able to create an html table and dynamically fill it as a user inputs information. The javascript will add the information dynamically to the first row and continue to do so as more information is added.
Updated HTML below:
<!DOCTYPE html>
<html lang="en">
<head>
<!--Required Meta Tag-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<style>
.center {
text-align: center;
border: 3px solid green;
}
body {
font-family: Arial;
margin: 0;
}
/* Header/Logo Title */
.header {
padding: 10px;
text-align: center;
background: #1abc9c;
color: white;
font-size: 20px;
}
table, td {
border: 1px solid black;
padding: 8px;
}
</style>
<title>Student Report Card</title>
</head>
<body>
<div class="header">
<br>
<h2>Student & Grade Input Form</h2>
<br>
</div>
<br>
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<input type="text" placeholder="Enter name" name="name" id="name" required><br>
<br>
<input type="email" placeholder="Enter Email" name="email" id="email" required><br>
<br>
<input type="number" placeholder="Enter Math Grade" name="math" id="math" required><br>
<br>
<input type="number" placeholder="Enter English Grade" name="eng" id="eng" required><br>
<br>
<input type="number" placeholder="Enter Social Studies Grade" name="sstd" id="sstd" required><br>
<br>
<button type="submit" id="btn1">Submit</button>
<br><br>
<table id="myTable">
<tr>
<td>Name</td>
<td>Email</td>
<td>Math Grade</td>
<td>English Grade</td>
<td>Social Studies Grade</td>
</tr>
</table>
</div>
<script src="scripts.js"></script>
</body>
</html>
Updated Javascript below:
var studentList = new Object()
function inputFunc(){
var fname = document.getElementById("name").value
var email = document.getElementById("email").value
var math = document.getElementById("math").value
var eng = document.getElementById("eng").value
var sstd = document.getElementById("sstd").value
var x = Math.floor((Math.random() * 100) + 1);
var y = x.toString();
studentID = "student".concat(y)
studentNumber = "student".concat(y)
var studentID = new Object();
studentID.name = fname
studentID.email = email
studentID.math = math
studentID.eng = eng
studentID.sstd = sstd
studentList[studentNumber] = studentID
// variable of javascript object, place each element in a variable with stringfy
var studentInformation = studentList[studentNumber]
console.log(typeof studentInformation)
var obj = String(studentInformation.name)
var obj1 = String(studentInformation.email)
var obj2 = String(studentInformation.math)
var obj3 = String(studentInformation.eng)
var obj4 = String(studentInformation.sstd)
var table = document.getElementById("myTable");
var row = table.insertRow(1);
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);
cell1.innerHTML = obj;
cell2.innerHTML = obj1;
cell3.innerHTML = obj2;
cell4.innerHTML = obj3;
cell5.innerHTML = obj4;
}
I think this is just an issue of adding items to objects. Here is an example
let studentInfo;
studentInfo.push({ name: "John", email: "john#gmail.com" });
This answer in incorrect.

Categories