I just started learning javascript few months ago. Recently i've been struggling to make this code work, but i end up messing up everything.
i want to make the reset button to clear user inputs?
Ive done several modification, but i couldn't still make it work. i dont know where i got it wrong.
Please i'll appreciate if anyone can assist me with this.
<div class=" DTRloading__form" style="display: block;">
<div class="form-container">
<div class="info">
</div>
<form class="form-inline">
<div class="form-group w-5 ">
<label for="red">Red Phase:</label>
<input type="number" class="form-control formInline" id="red" style="width: 80px">
</div>
<div class="form-group">
<label for="yellow">Yellow Phase:</label>
<input type="number" class="form-control formInline" id="yellow" style="width: 80px">
</div>
<div class="form-group">
<label for="blue">Blue Phase:</label>
<input type="number" class="form-control formInline" id="blue" style="width: 80px">
</div>
<div class="form-group">
<label for="neutral">Neutral:</label>
<input type="number" class="form-control formInline" id="neutral" style="width: 80px">
</div>
</form>
<label for="inputKVA" class="sr-only">DTR CAPACITY(Amp)</label>
<input type="number" id="inputKVA" class="form-control load" placeholder="DTR CAPACITY (KVA) *" required>
<button id="btnStart3" style="margin-top: 8px" class="btn btn2 btn-lg btn-primary btn-block ">Calculate</button>
</div>
<div class="output">
<h5 class="b-display">DTR Full Load Current is:</h5>
<div id="flA" class="form-control bill"></div>
<h5 class="b-display">The percentage Loading of this DTR is:</h5>
<div id="outputLoading" class="form-control bill"></div>
<!-- <div id="outputSum" class="form-control bill"></div>-->
<button id="btnRefresh3" class="btn btn2 btn-lg btn-primary btn-block">Reset</button>
</div>
</div>
<script>
document.getElementById("btnStart3").addEventListener('click', doCalc);
function doCalc() {
// Assign user inputs to variables
let x = parseFloat(document.querySelector("#red").value);
let y = parseFloat(document.querySelector("#yellow").value);
let z = parseFloat(document.querySelector("#blue").value);
let n = parseFloat(document.querySelector("#neutral").value);
const capacity = document.querySelector("#inputKVA");
const output2 = document.querySelector("#outputLoading");
const output3 = document.querySelector("#flA");
const start3 = document.getElementById("btnStart3");
const refresh3 = document.getElementById("btnRefresh3");
// // Call the average function
getAverage(x,y,z,n);
}
function getAverage(x,y,z,n) {
// Calculate the average
let average = ((((x + y + z + n) / 3) / (capacity.value * 1.391) )* 100);
// Display result to user
console.log(average);
outputLoading.innerHTML = average.toFixed(0) + "%";
//
}
const capacity = document.querySelector("#inputKVA");
function calculate(e) {
console.log(e);
e.preventDefault();
console.log("btnStart3 clicked");
var totalfLA = ((capacity.value * 1000) / (1.7321 * 415));
console.log(totalfLA);
flA.innerHTML = totalfLA.toFixed(1) + "A";
}
function emptyInput() {
console.log("emptied!");
outputKVA.innerHTML = "";
flA.innerHTML = "";
x.value = "";
y.value = "";
z.value = "";
n.value = "";
capacity.value = "";
output2.value = "";
output3.value = "";
}
btnStart3.addEventListener("click", calculate);
refresh3.addEventListener("click", emptyInput);
</script>
You can try in html with below button type as well.
<input type="reset" value="Reset">
If you want reset form from javascript then
document.getElementById("your-form-id").reset();
Change
1. <form class="form-inline">
2. refresh3.addEventListener("click", emptyInput);
to
1. <form class="form-inline" id="form">
2. document.getElementById("btnRefresh3").addEventListener("click", emptyInput);
3. function emptyInput() {
document.getElementById("form").reset();
}
Related
I have created a form which can be dynamically changed using the buttons included. These buttons allow for more input fields to be added/removed. The issue is that the input fields created are not posting any data/ Values in those fields not being added to the $POST array on the submit of the form.
The main functions below resposible for adding and removing rows is RemoveRows() and addRows()
What should happen is that on submit all values in the form should be "posted" then I can access all of those fields via $_POST["nameOfField"].
The way I have currently approached this is to create an input fields with the relevant id's and names then append that field to where the "hard coded" fields exists.
From my initial debugging none of the fields that have been added via javascript are in $Post which I have checked via var_dump($_REQUEST);
I have also seen that the nodes that are added are not elements of the form tag even though the nodes are added between the opening and closing tag. This can be seen in the doBeforeSubmit() Function where we can see all elements that are children of the and this never changes as rows are added/removed.
function showPlatforms() {
let nacellesOptions = ["Option1", "option2", "Option3"];
let milOptions = ["Option1", "option2", "Option3"]
let highOptions = ["Option1", "option2", "Option3"]
let entry = document.getElementById("vs")
let platfom = document.getElementById("platform")
if (platform.hasChildNodes()) {
var lastChild = platfom.lastElementChild
while (lastChild) {
platfom.removeChild(lastChild)
lastChild = platform.lastElementChild
}
}
if (entry.value == "Nacelles") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = nacellesOptions[i]
option.innerHTML = nacellesOptions[i]
platform.appendChild(option)
}
} else if (entry.value == "Military") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = milOptions[i]
option.innerHTML = milOptions[i]
platform.appendChild(option)
}
} else {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = highOptions[i]
option.innerHTML = highOptions[i]
platform.appendChild(option)
}
}
}
function formOptions() {
let entry = document.getElementById("type")
if (entry.value == "Engineering MAM") {
document.getElementById("WBS").disabled = false
document.getElementById("Desc").disabled = false
document.getElementById("ProName").disabled = false
} else {
document.getElementById("WBS").disabled = true
document.getElementById("Desc").disabled = true
document.getElementById("ProName").disabled = true
}
}
function formoptions2() {
let entry2 = document.getElementById("organisation")
if (entry2.value == "Aftermarket") {
document.getElementById("COT").disabled = false
document.getElementById("COC").disabled = false
} else {
document.getElementById("COT").disabled = true
document.getElementById("COC").disabled = true
}
}
count = document.getElementById("partNum").childElementCount
function addRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(addRow, count)
count = document.getElementById("partNum").childElementCount
//doBeforeSubmit()
}
function doBeforeSubmit() {
var es = document.getElementById("form").elements;
var l = es.length;
var msgs = [];
for (var idx = 0; idx < l; idx++) {
var e = es[idx];
msgs.push('name=' + e.name + ', type=' + e.type + ', value=' + e.value);
}
alert(msgs.join('\n'));
return false;
}
function addRow(id) {
let col = document.getElementById(id)
var box = document.createElement("INPUT")
box.setAttribute("type", "text")
box.setAttribute("id", id + count)
box.setAttribute("name", id + count)
box.setAttribute("class", "form-control")
col.appendChild(box)
}
function RemoveRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(removeBoxes)
count = document.getElementById("partNum").childElementCount
}
function removeBoxes(item) {
let box = document.getElementById(item)
let last = box.lastChild
box.removeChild(last)
}
function checkData() {
// if all stuff is correct do this:
document.getElementById("submit").disabled = false
// else dont activate the submit button.
}
<form method="post" id="form" action="SubmitMAM.php">
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNo" class="col-2">
<h3>Part Number:</h3>
</div>
<div class="col-2">
<h3>Part Description:</h3>
</div>
<div class="col-1">
<h3>Lead Time:</h3>
</div>
<div class="col-1">
<h3>Quantity:</h3>
</div>
<div class="col-1">
<h3>Date Required:</h3>
</div>
<div class="col-1">
<h3>Unit Cost:</h3>
</div>
<div class="col-2">
<h3>Unit Cost Extension:</h3>
</div>
<div class="col-1">
<h3>Unit Sale Value:</h3>
</div>
<div class="col-1">
<h3>Est Sales Value:</h3>
</div>
</div>
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNum" class="col-2">
<input type="text" id="partNum0" class="form-control" name="partNum0">
</div>
<div id="partDesc" class="col-2">
<input type="text" id="partDesc0" class="form-control" name="partDesc0">
</div>
<div id="leadTime" class="col-1">
<input type="text" id="leadTime0" class="form-control" name="leadTime0">
</div>
<div id="quantity" class="col-1">
<input type="text" id="quanitity0" class="form-control" name="quantity0">
</div>
<div id="dateReq" class="col-1">
<input type="text" id="dateReq0" class="form-control" name="dateReq0">
</div>
<div id="unitCost" class="col-1">
<input type="text" id="unitCost0" class="form-control" name="unitCost0">
</div>
<div id="unitExtention" class="col-2">
<input type="text" id="unitExtention0" class="form-control" name="unitExtention0">
</div>
<div id="unitSaleValue" class="col-1">
<input type="text" id="unitSaleValue0" class="form-control" name="unitSaleValue0">
</div>
<div id="estSalesValue" class="col-1">
<input type="text" id="estSalesValue0" class="form-control" name="estSalesValue0">
</div>
<button onclick="addRows()" class="btn btn-primary" type="button">Add a Product</button>
<button onclick="RemoveRows()" class="btn btn-primary" type="button">Remove Row</button>
<button onclick="checkData()" class="btn btn-primary" type="button">Check Data</button>
<br>
<button type="submit" name="submit" id="submit" class="btn btn-primary" disabled>Submit</button>
</form>
PHP:
<?php
var_dump($_REQUEST)
?>
UPDATE:
The code has been changed to use a php array by adding square brackets into the name which produces the following html:
<input type="text" id="partNum0" class="form-control" name="partNum[]">
<input type="text" id="partNum1" name="partNum[]" class="form-control">
<input type="text" id="partNum2" name="partNum[]" class="form-control">
You just need to use the name property of the input and add [] at the end, as GrumpyCrouton said. PHP parse it as an array, and you can access it as:
$partNum = $_POST["partNum"];
FIXED: It turns out the above code did not have any issues with the logic or the way it should work, in the source code in visual studio the indentation of some of the Divs was off causing the browser to have issues in rendering the form correctly hence why the added boxes were not included in the form and their values not POSTED.
As a heads up to anyone with maybe a similar issue, it pays to have your code neat.
I have three different inputs inside a modal that represents three different "stock" items. if a user adds a value in the input related to that specific item with a minimum of the value stipulated I want to add that input value to the total amount. but I'm stuck with looping over the buttons and calling the addAmount function to get the correct input.
I might be overcomplicating things as I'm quite new to this.
any guidance would be appreciated
const btns = document.querySelectorAll('.add-stock');
const inputs = document.querySelectorAll('[data-stock-amount]');
let totalAmount = document.querySelector('.total-amount');
totalValue = 5000;
const addAmount = (e) => {
inputs.forEach(input => {
let setAmount = input.value;
let inputData = input.dataset.stockAmount;
if (inputData === "stock25") {
totalValue = parseFloat(totalValue) + parseFloat(setAmount);
totalAmount.innerHTML = totalValue;
}
if (inputData === "stock50") {
totalValue = parseFloat(totalValue) + parseFloat(setAmount);
totalAmount.innerHTML = totalValue;
}
if (inputData === "stock100") {
totalValue = parseFloat(totalValue) + parseFloat(setAmount);
totalAmount.innerHTML = totalValue;
}
});
}
btns.forEach(btn => {
btn.addEventListener('click', (e) => {
let btnData = e.target.dataset.addStock;
if (btnData === inputData) {
addAmount(e);
}
});
});
<div class="total">$ <span class="total-amount">5000</span></div>
<div class="modal">
<div class="card">
<input type="number" name="stock1" id="stock1" value="25" data-stock-amount="stock25">
<label for="stock1">Stock1</label>
<button class="add-stock" data-add-stock="stock25">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock2" id="stock2" value="50" data-stock-amount="stock50">
<label for="stock2">Stock2</label>
<button class="add-stock" data-add-stock="stock50">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock3" id="stock3" value="100" data-stock-amount="stock100">
<label for="stock3">Stock3</label>
<button class="add-stock" data-add-stock="stock100">Add Stock</button>
</div>
</div>
Your code is significantly longer and more complicated than it needs to be. Here's a way to get you started:
const btns = document.querySelectorAll(".add-stock");
const totalAmount = document.querySelector(".total-amount");
/* Increment the total amount by the given amount. */
const addAmount = amount => {
// The '+' before the variable casts the value to a number.
totalAmount.innerHTML = +totalAmount.innerHTML + +amount;
}
btns.forEach(btn => {
btn.addEventListener("click", e => {
/* Cache the stock amount of the clicked button. */
let btnData = e.target.dataset.addStock;
/* Use the above value to find the related input. */
let input = document.querySelector("[data-stock-amount = '" + btnData + "']");
/* Parse the stock amount to find the default value. */
let defaultValue = +btnData.replace("stock", "");
/* If the current value exceeds or equals the default, add it. */
if (input.value >= defaultValue) addAmount(input.value);
/* Otherwise, print a warning on the console. */
else console.log(input.value + " is less than the default of " + defaultValue);
});
});
<div class="total">$ <span class="total-amount">5000</span></div>
<div class="modal">
<div class="card"><input type="number" name="stock1" id="stock1" value="25" data-stock-amount="stock25"><label for="stock1">Stock1</label>
<button class="add-stock" data-add-stock="stock25">Add Stock</button>
</div>
<div class="card"><input type="number" name="stock2" id="stock2" value="50" data-stock-amount="stock50"><label for="stock2">Stock2</label>
<button class="add-stock" data-add-stock="stock50">Add Stock</button>
</div>
<div class="card"><input type="number" name="stock3" id="stock3" value="100" data-stock-amount="stock100"><label for="stock3">Stock3</label>
<button class="add-stock" data-add-stock="stock100">Add Stock</button>
</div>
</div>
I believe this code meets your requirements, please see the code comments for details. This approach requires only 1 event listener to be added to a single parent element of the buttons we want to listener to click events for - this technique is called event delegation and is a cleaner approach than adding many event listeners:
const inputEls = document.querySelectorAll('[data-stock-amount]');
const totalAmountEl = document.querySelector('.total-amount');
// Get the initial values and store them as minimums
const minimumStockValues = Array.from(inputEls).reduce((map, stock) => {
map.set(stock.name, stock.value);
return map;
}, new Map());
// Add an event listener on the modal for button clicks
document.querySelector('.modal').addEventListener('click', event => {
if (event.target.tagName === 'BUTTON') {
// Get the input that corresponds to the button that was clicked
const inputEl = document.querySelector(`[data-stock-amount='${event.target.dataset.addStock}']`);
// Compare the value in the input with the allowable minimum amount and take some action
if (inputEl.value >= minimumStockValues.get(inputEl.name)) {
totalAmountEl.innerHTML = parseInt(totalAmountEl.textContent) + parseInt(inputEl.value);
} else {
console.error(`Minimum amount allowed for ${inputEl.name} is $${minimumStockValues.get(inputEl.name)}`);
}
}
});
<div class="total">$<span class="total-amount">5000</span></div>
<div class="modal">
<div class="card">
<input type="number" name="stock1" id="stock1" value="25" data-stock-amount="stock25">
<label for="stock1">Stock1</label>
<button class="add-stock" data-add-stock="stock25">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock2" id="stock2" value="50" data-stock-amount="stock50">
<label for="stock2">Stock2</label>
<button class="add-stock" data-add-stock="stock50">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock3" id="stock3" value="100" data-stock-amount="stock100">
<label for="stock3">Stock3</label>
<button class="add-stock" data-add-stock="stock100">Add Stock</button>
</div>
</div>
You are overcomplicating the logic. Just grab the input value and default value and get the max of it and add it to totalAmount.
const btns = document.querySelectorAll(".add-stock");
const inputs = document.querySelectorAll("[data-stock-amount]");
let totalAmount = document.querySelector(".total-amount");
btns.forEach((btn) => {
btn.addEventListener("click", (e) => {
const minValue = e.target.dataset.addStock.match(/[\d]+/g)[0];
const inputValue = e.target.parentNode.querySelector("input").value;
let totalAmountData = +totalAmount.textContent;
totalAmount.textContent = totalAmountData + Math.max(minValue, inputValue);
});
});
<div class="total">$ <span class="total-amount">5000</span></div>
<div class="modal">
<div class="card">
<input type="number" name="stock1" id="stock1" value="25" data-stock-amount="stock25">
<label for="stock1">Stock1</label>
<button class="add-stock" data-add-stock="stock25">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock2" id="stock2" value="50" data-stock-amount="stock50">
<label for="stock2">Stock2</label>
<button class="add-stock" data-add-stock="stock50">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock3" id="stock3" value="100" data-stock-amount="stock100">
<label for="stock3">Stock3</label>
<button class="add-stock" data-add-stock="stock100">Add Stock</button>
</div>
</div>
i'm having trouble going trough making a calculator (sum only) of 5 inputs fields in html/javascript and i can't manage to find what's wrong in my code
i tried messing around with types such as int instead of var and passing the value into parseInt, i somehow managed to have a result like "11111" where it should be like "5" but alongside that case the result is never printed in the innerHTML even after i added the "if not null" condition
Here is my html
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute();">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>
and here is my javascript
function ratingCompute()
{
var designValue = document.getElementById("design").value;
var plotValue = document.getElementById("plot").value;
var charValue = document.getElementById("character").value;
var enjoyValue = document.getElementById("enjoyment").value;
var musicValue = document.getElementById("music").value;
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
Any clue?
JavaScript is not a type variable language try using let or const. And here is how you properly parse it. If you did it already then its because of your variable declaration.
let designValue = parseInt(document.getElementById("design").value);
let plotValue = parseInt(document.getElementById("plot").value);
let charValue = parseInt(document.getElementById("character").value);
let enjoyValue = parseInt(document.getElementById("enjoyment").value);
let musicValue = parseInt(document.getElementById("music").value);
In javascript you should use keyword var/let/const instead of int. and you have to convert String type input value to int using parseInt method.
Please check this:
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute()">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>
As mentioned by #Joshua Aclan, JavaScript does not have an "int" variable declaration, only "var". Also you have to cast all of the inputs to int or float, because otherwise you are adding strings and the values of input fields are always strings. Also the output is most likely empty because int designValue... produces an error.
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
I've done this JavaScript calculation. Live Preview
Everything is okay but the problem is, Once the calculation is done, the next time it shows NAN value. If you do not reload the page, then you can not calculation!
I want to repeat the calculation without reloading, how could it be?
Here Is my Simple Calculation:
// get all data
var first = document.getElementById('first');
var second = document.getElementById('second');
var third = document.getElementById('third');
var four = document.getElementById('four');
var five = document.getElementById('five');
var six = document.getElementById('six');
var seven = document.getElementById('seven');
var eight = document.getElementById('eight');
var outPut = document.getElementById('result');
// Listen for Submit the form
document.getElementById('gpaInput').addEventListener('submit', outPutF);
function outPutF(e){
e.preventDefault();
// Calculation
first = first.value * 5 / 100;
second = second.value * 5 / 100;
third = third.value * 5 / 100;
four = four.value * 15 / 100;
five = five.value * 15 / 100;
six = six.value * 20 / 100;
seven = seven.value * 25 / 100;
eight = eight.value * 10 / 100;
var result = first + second + third + four + five + six + seven + eight;
// Reset the form
this.reset();
// Finally output the Calculation
outPut.innerHTML = 'Your CGPA: '+result;
// setTimeout(window.location.reload(true), 9000);
}
input:focus, button:focus, select:focus {outline: none!important;box-shadow: none!important;}
#gpaInput .input-group {margin: 0.5em 0;}
#gpaInput .input-group-text { min-width: 95px;}
#result {display: block; width: 68%; text-align: center; margin-top: 25px; padding: 17px 0;}
.jumbotron {overflow: hidden;}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6">
<form id="gpaInput">
<div class="input-group">
<input id="first" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="second" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="third" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="four" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="five" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="six" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="seven" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="eight" type="number" step="any" class="form-control">
</div>
<hr>
<div class="mt-4">
<button type="submit" class="btn btn-info float-left p-3">Calculate CGPA</button>
<h5 id="result" class="alert alert-success float-right mt-0">Complete The form!</h5>
</div>
</form>
</div>
</div>
</div>
You get NaN because you are replacing the reference to the element with its value , so on the second time it is not longer the element.
var first = document.getElementById('first'); //<-- element
first = first.value * 5 / 100; //<-- first replaced with a number
so than next time you call it
first = first.value * 5 / 100; //<-- first.value is undefined here since first is a number
So you need to rename your variables inside...
var nFirst = first.value * 5 / 100;
var nSecond = second.value * 5 / 100;
var nThird = third.value * 5 / 100;
var nFour = four.value * 15 / 100;
var nFive = five.value * 15 / 100;
var nSix = six.value * 20 / 100;
var nSeven = seven.value * 25 / 100;
var nEight = eight.value * 10 / 100;
var result = nFirst + nSecond + nThird + nFour + nFive + nSix + nSeven + nEight;
You Should Declare your variables inside your function or you can get the value of every fields inside the function so that when the code runs for the next time it will get the values again correctly,
// Listen for Submit the form
document.getElementById('gpaInput').addEventListener('submit', outPutF);
function outPutF(e){
var first = document.getElementById('first');
var second = document.getElementById('second');
var third = document.getElementById('third');
var four = document.getElementById('four');
var five = document.getElementById('five');
var six = document.getElementById('six');
var seven = document.getElementById('seven');
var eight = document.getElementById('eight');
var outPut = document.getElementById('result');
e.preventDefault();
// Calculation
first = first.value * 5 / 100;
second = second.value * 5 / 100;
third = third.value * 5 / 100;
four = four.value * 15 / 100;
five = five.value * 15 / 100;
six = six.value * 20 / 100;
seven = seven.value * 25 / 100;
eight = eight.value * 10 / 100;
var result = first + second + third + four + five + six + seven + eight;
// Reset the form
this.reset();
// Finally output the Calculation
outPut.innerHTML = 'Your CGPA: '+result;
// setTimeout(window.location.reload(true), 9000);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6">
<form id="gpaInput">
<div class="input-group">
<input id="first" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="second" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="third" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="four" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="five" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="six" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="seven" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="eight" type="number" step="any" class="form-control">
</div>
<hr>
<div class="mt-4">
<button type="submit" class="btn btn-info float-left p-3">Calculate CGPA</button>
<h5 id="result" class="alert alert-success float-right mt-0">Complete The form!</h5>
</div>
</form>
</div>
</div>
</div>
I am building a calculator, which I have previously asked questions on, see previous link: Building an interest rate calculator, however it won't produce figure
I want some fields to appear with commas when entered, I found some code on here and it seems to work with the formatting however now the calculations just return NaN.
Any ideas why adding commas would stop it from working?
Here's the code I used to add the commas and the code for the calculator is on the previous link:
HTML:
<div class="col-md-10 col-md-offset-1 form-body form-group">
<h2 class="form-heading">Find out how much your mortgage will cost</h2>
<div class="row text-muted">
<div class="col-md-5 col-md-offset-1 calc-input">
<h3>Purchase Price</h3>
<div class="input-group">
<span class="input-group-addon">£</span>
<input type="text" class="form-control comma" id="pp" placeholder="150,000" onchange="depositValue()">
</div>
<h3>Deposit</h3>
<div class="row text-muted">
<div class="col-md-4">
<div class="input-group">
<input type="text" class="form-control" id="percent" placeholder="10" onchange="depositValue()">
<span class="input-group-addon">%</span>
</div>
</div>
<div class="col-md-8">
<div class="input-group">
<span class="input-group-addon">£</span>
<input type="text" class="form-control comma" id="dp" placeholder="15,000" onchange="depositPercent()">
</div>
</div>
</div>
<h3>Mortgage Term</h3>
<div class="input-group">
<input type="text" class="form-control" id="mt" placeholder="25">
<span class="input-group-addon">Years</span>
</div>
<h3>Interest Rate</h3>
<div class="input-group">
<input type="text" class="form-control" id="ir" placeholder="4">
<span class="input-group-addon">%</span>
</div>
</div>
<div class="col-md-5 text-center">
<h3>Estimated Monthly Payment:</h3>
<p id="result"></p>
</div>
</div>
<div class="row text-muted">
<div class="col-md-10 col-md-offset-1 text-center">
<button class="btn btn-cta" onclick="calculate()">Calculate</button>
</div>
</div>
</div>
Calculator JS:
function calculate() {
var pp = document.getElementById("pp").value;
var dp = document.getElementById("dp").value;
var mt = document.getElementById("mt").value;
var ir = document.getElementById("ir").value;
var result = document.getElementById("result");
var la = parseInt(pp.replace(/,/g, ""), 10) - parseInt(dp.replace(/,/g, ""), 10);
var intRate = (ir/100)/12;
var months = mt * 12;
var monthlyPayment = ((((la*intRate)/(1-Math.pow(1+intRate,(-1*months)))*100)/100).toFixed(2));
result.innerHTML = "£" + monthlyPayment.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function depositValue() {
var pp = document.getElementById("pp").value;
var percent = document.getElementById("percent").value;
var dp = document.getElementById("dp");
var dpValue = (parseInt(percent.replace(/,/g, ""), 10) / 100) * parseInt(pp.replace(/,/g, ""), 10);
dp.value = dpValue;
}
function depositPercent() {
var pp = document.getElementById("pp").value;
var dp = document.getElementById("dp").value;
var percent = document.getElementById("percent");
var dpPercent = (parseInt(dp.replace(/,/g, ""), 10) / parseInt(pp.replace(/,/g, ""), 10) * 100).toFixed(0);
percent.value = dpPercent;
}
Comma JS (in another file):
$('input.comma').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
The moment you add the commas, it's no longer a number, but a string. When you do your calculations you'll have to account for that by stripping them out before processing.