I have a field "total" which calculates the product of 'price per kWH, 'KwH', and 'Hours used'. I would like to dynamically change the output of all 'total' fields if the user retrospectively changes the value of 'price per KwH'. Currently, only the latest added total field recalculates the product when changing the price value.
var idNumber= 1;
var deviceID = "device_"+idNumber;
var kWattID = "kW_"+idNumber;
var hoursID = "hours_"+idNumber;
var totalID = "total_"+idNumber;
function createNewInputFields() {
// console.log("In createNewInputFields - Given number:"+idNumber);
idNumber = idNumber+1;
// console.log("In createNewInputFields - after increase:"+idNumber);
deviceID = "device_"+idNumber;
kWattID = "kW_"+idNumber;
hoursID = "hours_"+idNumber;
totalID = "total_"+idNumber;
// console.log("In createNewInputFields() - "+deviceID);
// console.log("In createNewInputFields() - "+kWattID);
// console.log("In createNewInputFields() - "+hoursID);
// console.log("In createNewInputFields() - "+totalID);
const containerDevice = document.getElementById('deviceCol');
const containerkWatt = document.getElementById('kWattsCol');
const containerHours = document.getElementById('hoursCol');
const containerTotal = document.getElementById('totalCol');
const inputHtmlDevice = "<input type='text' id="+deviceID+" required>";
const inputHtmlkWatt = "<br> <input type='text' oninput='calculate()' id="+kWattID+" required>";
const inputHtmlHours = "<input type='text' oninput='calculate()' id="+hoursID+" required>";
const inputHtmlTotal = "<input type='text' id="+totalID+" required readonly>";
containerDevice.insertAdjacentHTML('beforeend', inputHtmlDevice);
containerkWatt.insertAdjacentHTML('beforeend', inputHtmlkWatt);
containerHours.insertAdjacentHTML('beforeend', inputHtmlHours);
containerTotal.insertAdjacentHTML('beforeend', inputHtmlTotal);
return idNumber;
}
// function to correctly round up to the third decimal
function precisionRound(number) {
var factor = Math.pow(10, 4);
return Math.round(number * factor) / factor;
}
function calculate(){
// console.log("In calculate() - idNumber: "+idNumber);
deviceID = "device_"+idNumber;
kWattID = "kW_"+idNumber;
hoursID = "hours_"+idNumber;
totalID = "total_"+idNumber;
// console.log("In calculate() - : "+deviceID);
// console.log("In calculate() - : "+kWattID);
// console.log("In calculate() - : "+hoursID);
// console.log("In calculate() - : "+totalID);
var kW = document.getElementById(kWattID).value;
var kW = parseFloat(kW).toFixed(3);
var hours = document.getElementById(hoursID).value;
var hours = parseFloat(hours).toFixed(3);
var kwH_rate = document.getElementById("energyrate").value
var total = kwH_rate * (kW * hours);
var total = precisionRound(total)
document.getElementById(totalID).value = total;
}
body {
background: transparent;
color: #fcbe24;
padding: 0 24px;
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<div class="intro">
<p> Enter your energy company's electricity rate per kWh: <input type="text" class="energyrate" oninput="calculate()" id="energyrate" required></p>
</div>
<div class="row">
<div class="deviceCol" id="deviceCol">
<p><b>Device</b></p>
<input type="text" id="device_1" required>
<!-- device name watts hours in use total -->
</div>
<div class="kWattsCol" id="kWattsCol">
<p><b>kWh</b></p>
<input type="text" oninput="calculate()" id="kW_1" required>
<!-- <input type="text" id="kW_1" required> -->
</div>
<div class="hoursCol" id="hoursCol">
<p><b>Hours used</b></p>
<input type="text" oninput="calculate()" id="hours_1" required>
<!-- <input type="text" onkeypress="calculate(idNumber)" id="hours_1"required> -->
</div>
<div class="totalCol" id="totalCol">
<p><b>Total</b></p>
<input type="text" id="total_1" readonly>
</div>
<button class="btn" onclick="createNewInputFields(idNumber)">Add another item</button>
</div>
<h1 id="header"></h1>
<script src="src/script.js"></script>
</body>
</html>
Related
I have an html form with item and amount entries and I want the values in them to be stored in local storage and xampp, I have succeeded in submiting to localstorage however the form submits nothing in xampp in a column for item and 0 in the column of amount
here is my html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>ICT specialists</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="app.css" />
<link rel="shortcut icon" href="ICT_Logo-01.png">
</head>
<body>
<h2>Daily transactions at ICT specialists</h2>
<div class="container">
<h4>Your balance</h4>
<h1 id="balance"></h1>
<div class="inc-exp-container">
<div>
<h4>income</h4>
<p id="money-plus" class="money plus"></p>
</div>
<div>
<h4>expense</h4>
<p id="money-minus" class="money minus"></p>
</div>
</div>
<h3>History</h3>
<div class="shows">
<ion-icon name="menu-outline" id="showLi"></ion-icon>
<ion-icon name="close-outline" id="hideLi"></ion-icon>
</div>
<ul id="list" class="list"></ul>
<h3>add new transation</h3>
<form action="sales.php" method="post" id="form">
<div class="form-control">
<label for="">date</label>
<input type="text" id="date" name="date">
</div>
<div class="form-control">
<label for="text">item</label>
<input type="text" id="text" name="item" placeholder="please enter the item..." autocomplete="off" />
</div>
<div class="form-control">
<label for="amount">amount <br />(negative=expense, positive=income)</label>
<input type="number" id="amount" name="amount" placeholder="please enter the amount..." autocomplete="off" />
</div>
<button class="btn" type="submit">Add transation</button>
</form>
</div>
<div class="footer">
<div class="footerTxt">copyright © <span id="dated">2022</span</div>
<div class="footerRyt">
ict specialists | sydotech
</div>
</div>
<style>
.footer{
display: flex;
justify-content: space-evenly;
width: 100%;
bottom: 0;
background: deepskyblue !important;
padding: 10px;
position: fixed;
}
.footer .footerTxt{
font-size: 1.2rem;
text-transform: capitalize;
font-weight: 500;
}
.footer .footerRyt a{
text-decoration: none;
font-size: 1.4rem;
color: #fff !important;
}
</style>
<ion-icon name="arrow-up-outline" id="icons"></ion-icon>
<script src="sales.js"></script>
<script type="module" src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.esm.js">
</script>
<script nomodule src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.js"></script>
</body>
</html>
here is my php
<?php
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=sales','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
if($_SERVER['REQUEST_METHOD']==='POST'){
$item = $_POST['item'];
$amount = $_POST['amount'];
$statement = $pdo->prepare("insert into transaction
(item,amount)
values (:item,:amount)");
$statement->bindValue(':item', $item );
$statement->bindValue(':amount', $amount );
$statement->execute();
header('Location: sales.html');
}
here is my javascript file
const balance = document.getElementById("balance");
const money_plus = document.getElementById("money-plus");
const list = document.getElementById("list");
const form = document.getElementById("form");
const text = document.getElementById("text");
const amount = document.getElementById("amount");
const money_minus = document.getElementById("money-minus");
let showLi = document.getElementById("showLi");
let hideLi = document.getElementById('hideLi');
const localStorageTransations = JSON.parse(localStorage.getItem("transations"));
let transations =
localStorage.getItem("transations") !== null ? localStorageTransations : [];
//add transation
function addTransation() {
// e.preventDefault();
if (text.value.trim() === "" || amount.value.trim() === "") {
text.placeholder = "PLEASE SOME TEXT";
text.style.backgroundColor = "#ccc";
text.style.fontWeight = 'bold';
amount.placeholder = "ENTER AMOUNT";
amount.style.backgroundColor = "#ccc";
amount.style.fontWeight = 'bold';
} else {
const transation = {
id: genenrateID(),
text: text.value,
amount: +amount.value,
};
transations.push(transation);
addTransationDOM(transation);
updateValues();
updateLocalStorage();
text.value = "";
amount.value = "";
}
}
//generate id
function genenrateID() {
return Math.floor(Math.random() * 100000000);
}
//add transations to dom list
function addTransationDOM(transation) {
//get sign
const sign = transation.amount < 0 ? "-" : "+";
const item = document.createElement("li");
//add class based on value
item.classList.add(transation.amount < 0 ? "minus" : "plus");
item.innerHTML = `${transation.text} <span>${sign}${Math.abs(transation.amount)}</span>
<button class="delete-btn" onclick="removeTransation(${transation.id})">x</button>`;
list.appendChild(item);
item.style.display="none";
hideLi.addEventListener('click',()=>{
item.style.display = 'none';
hideLi.style.display = "none";
showLi.style.display = "block";
});
showLi.addEventListener('click',()=>{
item.style.display = 'block';
hideLi.style.display = "block";
showLi.style.display = "none";
})
}
// ********hide list******
// ********hide list end******
//update the balance
function updateValues() {
const amounts = transations.map((transation) => transation.amount);
const total = amounts.reduce((acc, item) => (acc += item), 0).toFixed(0);
const income = amounts
.filter((item) => item > 0)
.reduce((acc, item) => (acc += item), 0)
.toFixed(0);
const expense = (
amounts.filter((item) => item < 0).reduce((acc, item) => (acc += item), 0) * -1).toFixed(0);
balance.innerText = `UgShs: ${total}`;
money_plus.innerText = `UgShs: ${income}`;
money_minus.innerText = `UgShs: ${expense}`;
}
//remove
function removeTransation(id) {
transations = transations.filter((transation) => transation.id !== id);
updateLocalStorage();
init();
}
//updatelocal storage
function updateLocalStorage() {
localStorage.setItem("transations", JSON.stringify(transations));
}
function init() {
list.innerHTML = "";
transations.forEach(addTransationDOM);
updateValues();
}
init();
form.addEventListener("submit", addTransation);
// *********date calculation********
let date =document.getElementById('date');
date.value = new Date().toDateString();
// *********ionicons*******88
let icon = document.getElementById('icons');
window.onscroll = ()=>{
if(window.scrollY >=100){
icon.style.display = 'block';
icon.style.position = 'fixed';
}else{
icon.style.display = 'none';
}
}
icon.addEventListener('click',()=>{
window.scrollTo({top:0, behavior:"smooth"})
})
let span11 = document.getElementById('dated');
span11.innerHTML = new Date().getFullYear();
This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 1 year ago.
I get 4.5.525 when adding in javascript
this is the answer i have to get 4.5 + .525 = 5.025 but instead of this i get 4.5.525
here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<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>Swinburnes Test Of Dc Shunt Motor</title>
<style>
body {
padding: 25px;
background-color: white;
color: black;
font-size: 15px;
background: var(--primary-color);
transition: background 2s;
}
.dark-mode {
background-color: black;
color: white;
}
</style>
</head>
<body>
<div style="text-align: center;" class="container col-xs-12 col-md-4">
<h1 style="font-size: 2em;">Swinburnes Calculator (Motor) <span><button class="btn btn-dark badge badge-dark "
style=" margin-left: 101px;
font-size: 12px;" onclick="myFunction()">Dark mode</button></span> </h1>
<div class="inpSection">
<div class="amt">
<label for="VL">VL</label>
<input type="number" name="VL" id="VL" placeholder="Enter VL Value In Name Plate"
style="margin: 2%; margin-left: 6%;">
</div>
<div class="time">
<label for="IL">IL</label>
<input type="number" name="IL" id="IL" placeholder="Enter IL Value"
style="margin: 2%;margin-left: 7%; ">
</div>
<div class="rate">
<label for="Ish">Ish</label>
<input type="number" name="Ish" id="Ish" placeholder="Enter Ish Value"
style="margin: 2%;margin-left: 5%;">
</div>
<div class="rate">
<label for="Ra">Ra</label>
<input type="number" name="Ra" id="Ra" placeholder="Enter Ra value" style="margin: 2%;margin-left: 6%;">
</div>
<div class="rate">
<label for="Load">Load</label>
<input type="number" name="Load" id="Load" placeholder="Enter Load value In Name Plate" style="margin: 2%;">
</div>
<div class="rate">
<label for="noLoad">VL</label>
<input type="number" name="noLoad" id="noLoad" placeholder="Enter NoLoad VL value" style ="margin:2%; margin-left: 6%">
</div>
<div class="button">
<button class="btn btn-success" onclick="Calculate()" style="margin: 2%;
text-align: center;
;
margin-top: 5%;">Calculate</button>
<button class= "btn btn-danger" style="margin: 2%;
text-align: center;
;
margin-top: 5%;" onclick="refreshPage()">Reset All</button>
</div>
<script>
function refreshPage(){
window. location. reload();
}
</script>
<div class="result" style="margin-top: 30px;">
<h3 id="si"></h3>
<h3 id="wv"></h3>
<h3 id="Ip"></h3>
<h3 id="Wc"></h3>
<h3 id="toloss"></h3>
<h3 id="Oppower"></h3>
<h3 id="Eff"></h3>
</div>
</div>
<hr style="height:1px;border:none;color:#333;background-color:#333;" />
<p style=" text-align: center;
margin-top: 30px;">Copyright ©️ 2021 AJB</p>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
<script>
function Calculate() {
let vl = document.getElementById('VL').value;
let il = document.getElementById('IL').value;
let ish = document.getElementById('Ish').value;
let ra = document.getElementById('Ra').value;
let ld = document.getElementById('Load').value;
let vlo = document.getElementById('noLoad').value;
let SI = (vl * ld)
document.getElementById('si').innerHTML = "O/P : " + SI;
var Iao = (ld+ish);
console.log(Iao)
var WV = (Math.pow(Iao, 2) * ra)
document.getElementById('wv').innerHTML = "Wv : " + WV;
let IP = (vl * il)
document.getElementById('Ip').innerHTML = "No Load I/P Power : " + IP;
var ip21 = (vl*il)
var WcIa = (il - ish)
var WvIa = (Math.pow(WcIa, 2) * ra)
var Wc = (IP - WvIa)
document.getElementById('Wc').innerHTML = "Wc : " + Wc;
var TLoss = (WV + Wc)
document.getElementById('toloss').innerHTML = " Total Loss : " + TLoss;
var OP = (SI + TLoss)
document.getElementById('Oppower').innerHTML = "Input Power : " + OP;
var ef = (SI / OP) * 100
document.getElementById('Eff').innerHTML = " η % : " + ef;
}
</script>
<script>
function myFunction() {
var element = document.body;
element.classList.toggle("dark-mode");
}
</script>
</html>
when i add IL = 4.5 and Ish = .525 it gives 4.5.525 in the console what to do ?
but the orginal answer it should show is 5.025
rewrite the code and comment it below so i can understand more clearly
when i write same in the javascript it gives me the correct answer
Try something like this:
var lat = (parseFloat(document.getElementById('VL').dataset.value));
That's how to save in variable 'var' the document.getElementById('VL') values and make them float, so now it won't see it as a string and hopefully it will let you sum them and get the number you need.
I have a form that asks for info about employees, their name, age, position and details, this then has to be added to a div when a "Add Record" button is pressed.
Currently I have the Object Constructor setup but i'm a little lost on how to push the details to the div and how i should write the function to do so, previously i used a Canvas to display it.
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<title>52DA session 5</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Quicksand"
rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="../css/employee_styles.css"/>
</head>
<body>
<div id="container">
<header>
<h1 id="heading" class="blueTxt">Employee Records</h1>
</header>
<div class="left">
<form>
<fieldset>
<legend><h2>Employee Details Entry</h2></legend>
<p class=><label>Name: <input class="text" type="text" id="name"
/></label></p>
<p><label>Age: <input class="text" type="text" id="age" /> c
</label></p>
<p><label>Position: <input class="text" type="text"
id="position" /></label></p>
<p><label>Details: <textarea type="text" id="details"
maxlength="114" ></textarea></label></p>
<input class="button" type="button" id="addRecord" onclick=""
value="Add Record"/>
</fieldset>
</form>
<div class="sort">
<h3>Sort</h3>
<button class="button" id="sortByName">By Name</button>
<button class="button" id="sortByAge">By Age</button>
<br/><button class="button" id="reset">Reset Details</button>
<br /><br />
</div>
</div>
<section>
<div id="employeeRecords">
</div>
</section>
</div>
<script src="../js/employee_script.js"></script>
</body>
</html>
var employees = [];
and my Javascript
//-------------------------------------------------------------------------
-------------------------------------
function Person(name, age, pos, dtls, img){
this.fullName = name;
this.employeeAge = age;
this.position = pos;
this.details = dtls;
this.avatarSrc = img;
this.createProfile = function(){
var profile = document.createElement("div");
profile.className = "profileStyle";
var avatar = document.createElement("img");
avatar.src = this.avatarSrc;
avatar.alt = this.fullName();
profile.appendChild(avatar);
var profileTxt = document.createElement("p");
profileTxt.innerHTML = "<b>" + this.fullName() +
"</b><br />" + this.age +
"</b><br />" + this.pos +
"</b><br />" + this.dtls;
profile.appendChild(profileTxt);
return profile;
}
employees.push(this);
}
for(var i=0; i < staff.length; i++){
document.getElementById("staff_list").appendChild(staff[i].createProfile());
}
//------------------------------------------------------------------------
-----------------------------------
function compareNames(a, b){
var nameA = //TODO - needs to refer to the employee name
var nameB = //TODO - needs to refer to the employee name
var result = 0;
if (nameA < nameB){
result = -1;
}
else if(nameA > nameB){
result = 1;
}
return result;
}
//-------------------------------------------------------------------------
-------------------------------------
function sortName(){
}
//--------------------------------------------------------------------------
------------------------------------
function sortAge(){
}
//-------------------------------------------------------------------------
-------------------------------------
function addRecord(){
}
//-------------------------------------------------------------------------
-------------------------------------
function writeRecords(){
//-------------------------------------------------------------------------
------------------------------------
function resetArray(){
}
//--------------------------------------------------------------------------
------------------------------------
function arrayButtons(){
}
You can do something like this.
elements = document.getElementById("myForm").elements;
for (var i = 0; i < elements.length; i++) {
var name = elements[i].name;
var val = elements[i].value;
name = name[0].toUpperCase() + name.slice(1);
var dsply = document.getElementById("dsply");
dsply.innerHTML += "<p>" + name + ": " + val + "</p>";
}
<form id="myForm" name="myForm">
<p>Title of the form</p>
<input type="text" name="user" value="Jon" />
<input type="age" name="age" value="26" />
<input type="text" name="pos" value="CEO" />
<textarea name="details">Enter Details here</textarea>
</form>
<div id="dsply">
</div>
I'm kinda new to programming and I cant solve this problem. The paragraphs are coming out like a stair case.
p
p
p
p
p
The p's are examples, but here is all the code I have done so far.
Keep in mind I'm not the best at css(I'm still learning)
All help would be appreciated
Please show me on how I an fix this problem, and tell me where in my code is this problem occurring.
I tried google but couldn't find anything...
var house = {}
function House() {
var msg = 'This house is painted'
var bath;
var bed;
var cook;
var Paint = document.getElementById('paint').value;
var square = document.getElementById('Square').value;
var bath = document.getElementById('bath').value;
var bed = document.getElementById('Bed').value
var cook = document.getElementById('Cook').value;
//Get paragraphs to store values
var paint = document.getElementById('isPaint');
var squareFeet = document.getElementById('sq_Feet')
var bathRoom = document.getElementById('bathroom')
var bedRoom = document.getElementById('BedRoom')
var kitchen = document.getElementById('kitchen');
if(Paint == 'Yes' || Paint == 'yes') {
house['isPainted'] = true;
paint.innerHTML = msg;
}
else if(Paint == 'No' || Paint == 'no') {
house['isPainted'] = false;
var msg = 'this house is not painted'
paint.innerHTML = msg;
}
else if(Paint == '') {
house['isPainted'] = undefined;
var msg = 'no details given';
paint.innerHTML = msg;
}
if(square != '' ) {
var squareFeetMsg = 'the house is';
squareFeet.innerHTML = squareFeetMsg + ' ' + document.getElementById('Square').value + ' square feet';
house['squareFeet'] = document.getElementById('Square').value
}else {
var squareFeetMsg = 'No Details Given';
squareFeet.innerHTML = squareFeetMsg;
}
}
body {
width: auto;
height: auto;
}
#houseDtails{
width: 350px;;
}
#container {
width: auto;
height: auto;
}
.houseDetails {
height: 0px;
float: right;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>House App</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div id="conatainer">
<div id="houseDtails">
<label for="paint">Is this house painted: </label><br>
<input type="text" id="paint" class="Detail" /><br>
<label for="Square">How many SQ feet does this have? :</label>
<input type="text" id="Square"><br>
<label for="bath">How many bathrooms does your house have</label>
<input type="text" id="bath"><br>
<label for="Bed">How many bedrooms dos your house have</label>
<input type="text" id="Bed"><br>
<label for="Cook">Does your house have a kitchen</label>
<input type="text" id="Cook"><br>
<input type="submit" name="" id="sub" class="subm" onclick="House()">
</div>
<div id="addDetailsToPage">
<p id="isPaint" class="houseDetails"></p>
<p id="sq_Feet" class="houseDetails"></p>
<p id="bathroom" class="houseDetails"></p>
<p id="Bedroom" class="houseDetails"></p>
<p id="Kitchen" class="houseDetails"></p>
</div>
</div>
<script src="House.js"></script>
</body>
The reason for the paragraphs rendering in that manner is result of float set on .houseDetails.
.houseDetails {
height: 0;
float: right;
}
This is because you have float: right; in your CSS for .houseDetails. Remove it and you should have your p aligned on the left below one another
What is wrong with my code? It is supposed to create input tags in html with using the incoming number (quantity):
// Declare variables
var numberOfGrades = 0;
var NL = "\n";
// Functions
function setQuantity() {
numberOfGrades = document.getElementById("quantity").value;
var inputBox = document.createElement("INPUT");
var BR = document.createElement("br"); // Break line
var gradeNumber = 1;
var gradeText = document.createTextNode("Grade " + gradeNumber + ":");
for (var i = 0; i < numberOfGrades; i++) {
alert(numberOfGrades);
document.getElementById("formDiv").appendChild(BR);
document.getElementById("formDiv").appendChild(gradeText);
document.getElementById("formDiv").appendChild(inputBox);
gradeNumber++;
}
}
body {
font-family: "Open Sans", sans-serif;
}
.container {
width: 100%;
background-color: lightcyan;
padding: 10px;
}
<body>
<h1>Homework and Quiz average calculator</h1>
<p>Please Enter the required information to calcuate</p>
<div class="container" id="formDiv">
<form id="formID">
<p>
<strong>Calculate the average of homework grades</strong>
</p>
How many grades?
<input type="number" id="quantity" name="quantity" min="1" max="10" value="1">
<!--<input onclick="setQuantity()" type="submit" value="Apply">-->
</form>
<button onclick="setQuantity()">APPLY</button>
<br>
</div>
<script src="script.js"></script>
</body>
JSFiddle here
When you call x.appendChild(y) the node y is added as a child from x removing it from where it was if already in the DOM.
For example:
var x = document.createElement("div");
var y = document.createElement("div");
var z = document.createElement("div");
x.appendChild(y);
z.appendChild(y); // now y is not inside x any more, was **moved** to z
If you want to have multiple nodes you need to create them inside the loop.