The program is supposed to determine how many months it will take to pay off the loan. Cannot seem to figure out how to fix my mathematical calculations. Not sure if it's the while loop that's wrong. Instead of determining the monthly payment based on user input, the input shows the total number of months (which i do not want. the program is supposed to do that). It is supposed to look like this: http://snag.gy/9vzGi.jpg Here is the code:
<html>
<head>
<title></title>
<script type="text/javascript">
function fixVal(value,numberOfCharacters,numberOfDecimals,padCharacter) {
var i, stringObject, stringLength, numberToPad;
value = value * Math.pow(10,numberOfDecimals);
value = Math.round(value);
stringObject = new String(value);
stringLength = stringObject.length;
while(stringLength < numberOfDecimals) {
stringObject = "0"+stringObject;
stringLength=stringLength+1;
}
if(numberOfDecimals>0) {
stringObject=stringObject.substring(0,stringLength-numberOfDecimals)+"."+
stringObject.substring(stringLength-numberOfDecimals,stringLength);
}
if (stringObject.length<numberOfCharacters && numberOfCharacters>0) {
numberToPad=numberOfCharacters-stringObject.length;
for (i=0; i<numberToPad; i=i+1) {
stringObject=padCharacter+stringObject;
}
}
return stringObject;
}
function buildTable() {
var amount=parseFloat(document.getElementById("loanAmt").value );
var numpay=parseInt(document.getElementById("monthlyPay").value );
var rate=parseFloat(document.getElementById("intRte").value );
rate = rate / 100;
var monthly = rate / 12;
var payment = ((amount * monthly) / (1-Math.pow((1 + monthly), - numpay)));
var total = payment * numpay;
var interest = total - amount;
var msg = "<table border='4' width='75%'>";
msg += "<tr>";
msg += "<td>Month</td>";
msg += "<td>Principal Paid</td>";
msg += "<td>Interest Paid</td>";
msg += "<td>Loan Balance</td>";
msg += "</tr>";
newPrincipal=amount;
var i = 1;
while (i <= numpay) {
newInterest=monthly*newPrincipal;
reduction=payment-newInterest;
newPrincipal=newPrincipal-reduction;
msg += "<tr><td align='left' bgcolor='pink'>"+i+"</td> \
<td align='left' bgcolor='pink'>"+fixVal(reduction,0,2,' ')+"</td> \
<td align='left' bgcolor='pink'>"+fixVal(newInterest,0,2,' ')+"</td> \
<td align='left' bgcolor='pink'>"+fixVal(newPrincipal,0,2,' ')+"</td></tr>";
i++;
}
msg += "</table>";
document.getElementById("results").innerHTML = msg;
}
</script>
<style type="text/css">
body {
background: black;
font-family: arial;
}
#contentwrap {
width: 700px;
margin: 40px auto 0px auto;
background: #FFFFCC;
text-align: center;
border: 6px red solid;
border-radius: 10px;
padding: 40px;
}
table {
border: 5px blue double;
background-color: #FFFFCC;
}
#header {
text-align: center;
font-size: 2.5em;
text-shadow: yellow 3px 3px;
margin-bottom: 18px;
color: red;
}
#button {
background: blue;
color: white;
cursor: pointer;
padding: 5px 0px 5px 0px;
border: 1px solid red;
border-radius: 25px;
width: 150px;
}
.contentTitles {
color: green;
font-weight: bold;
}
.style {
background: lightblue;
font-family: comic sans ms;
border: 6px blue double;
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<div id="contentwrap">
<div id="header">Javascript Loan Calculator</div>
<form>
<div class="contentTitles">Enter Loan Amount<br />
<input type="text" id="loanAmt" class="style"><p />
Interest Rate (%)<br />
<input type="text" id="intRte" class="style"><p />
Monthly Payment Amount<br />
<input type="text" id="monthlyPay" class="style"><p />
<div style="margin-top:20px;">
<input type="button" value="Process Data" id="button" onClick="buildTable()">
</div>
</form>
<center>
<div id="results" style="margin-top:20px;"></div>
</center>
</div> <!-- ends div#contentwrap -->
</body>
</html>
If you want the input to be the monthly payment, please don't call the respective variable numpay.
In your case, it seems more practical not to calculate the number of months beforehand. You can use the while loop to build the table and calculate the duration of the loan at the same time:
function buildTable() {
var amount = parseFloat(document.getElementById("loanAmt").value );
var monthly = parseInt(document.getElementById("monthlyPay").value );
var rate = parseFloat(document.getElementById("intRte").value );
rate = rate / 100 / 12;
var m = 0; // number of months
while (amount > 0) {
var interest = amount * rate;
var principal = monthly - interest;
if (principal > amount) {
principal = amount;
amount = 0.0;
} else {
amount -= principal;
}
// build table: m + 1, principal, interest, amount
m++;
}
// display table
}
Related
i would like create a table, where one column would be variables and i want to have "+" and "-" buttons next to it. So when i click button "+" it would show number input and after submit, it would add to the value.
It works for one value, but do not get the other right, without copying whole script.
<!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>Table</title>
</head>
<style>
body {
background-color: lightslategray;
}
#PLA {
float: left;
width: 30%;
padding: 10px;
}
th, td {
border: 1px solid;
}
.header {
text-align: center;
font-size: 20px;
}
.celltext {
font-size: 15px;
}
.number {
text-align: center;
}
.vbutton {
background-color: gray;
border: 1px solid black;
border-radius: 6px;
color: white;
text-align: center;
text-decoration: none;
font-size: 10px;
padding: 0px;
margin-right: 4px;
width: 20px;
height: 20px;
float: right;
}
button:hover {
background-color: lightgray;
color: black;
}
.input {
padding: 0px;
width: 48px;
height: 16px;
font-size: 14px;
-webkit-appearance: none;
}
input[type = number] {
-moz-appearance: textfield;
}
input:focus {
border: 0px;
outline: 0px;
}
</style>
<body>
<table id="PLA">
<div>
PLA
<span id="test"></span>
<input type="number" class="input" id="nwpla" onchange="changewpla1()" onkeypress="return onlyNumberKey(event)">
</div>
<tr class="header">
<td>Barva</td>
<td>Výrobce</td>
<td>Hmotnost (g)</td>
<td>Cena (kg)</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla1">
<span id="wpla1"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla2">
<span id="wpla2"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
</table>
</body>
<script>
// test
test = document.getElementById("test");
// Weight of pla1
wpla1 = document.getElementById("wpla1");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla1weight = localStorage.pla1weight;
localStorage.setItem("pla1weight", pla1weight);
if (localStorage.pla1weight == "undefined" || localStorage.pla1weight == isNaN) {
localStorage.pla1weight = 0
pla1weight = 0;
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
else {
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
function changewpla1() {
x = parseInt(wpla1.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla1weight = x - y;
} else {
pla1weight = x + y;
}
wpla1.innerHTML = pla1weight;
wpla1.value = pla1weight;
localStorage.setItem("pla1weight", pla1weight);
nwpla.style.display = "none";
}
// Weight of pla2
wpla2 = document.getElementById("wpla2");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla2weight = localStorage.pla2weight;
localStorage.setItem("pla2weight", pla2weight);
if (localStorage.pla2weight == "undefined" || localStorage.pla2weight == isNaN) {
localStorage.pla2weight = 0
pla2weight = 0;
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
else {
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
function changewpla2() {
x = parseInt(wpla2.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla2weight = x - y;
} else {
pla2weight = x + y;
}
wpla2.innerHTML = pla2weight;
wpla2.value = pla2weight;
localStorage.setItem("pla2weight", pla2weight);
nwpla.style.display = "none";
}
function addpla() {
nwpla.value = 0;
p = 0;
nwpla.style.display = "";
}
function subpla() {
nwpla.value = 0
p = 1;
nwpla.style.display = "";
}
function onlyNumberKey(evt) {
var ASCIICode = (evt.which) ? evt.which : evt.keyCode
if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
return false;
return true;
}
</script>
</html>
Any idea?
I would like to have a database as last option. Every value would be saved in local storage.
Thanks.
I have created an application to calculate BMI. Basically, here is how I'd like the application to work and wrote below so far:
You just enter your height in inches and enter weight in pounds.
The application will calculate your BMI, then tell you whether you are underweight, normal, obese, or overweight.
In case you enter a non-positive value for either height or weight, the program will show you an error message that "Invalid input. Enter a positive number.", and it will highlight the boxes that you need to fix/enter a valid value.
I have encountered 2 problems.
I can get the program to show the BMI result, but currently I don't know how to write to get the program to show whether the user is underweight, normal, obese, or overweight.
If BMI < 18.5 then underweight, BMI >= 18.5 and <=24.99 then normal, BMI > 25 and <=29.99 then obese, and BMI > 30 then overweight.
I would like to show the error (that tells user to enter positive values, not missing or negative values) as messages below the "Calculate BMI" button, not as an alert like "This page says - Invalid input for weight, enter a non-negative number." In other words, I would like to keep the same message but not using "alert" method.
How may I fix these problems please? I have attached both my HTML and my CSS codes below.
Thank you so much!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BMI Calculation</title>
<link rel="stylesheet" href="bmi.css">
</head>
<body>
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight'/><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight'/><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
<div class="results"></div>
</main>
<script>
var processEntries = function() {
var heightInputBox = document.getElementById("boxHeight");
var weightInputBox = document.getElementById("boxWeight");
var outputBMI = document.querySelectorAll("div.results");
outputBMI[0].textContent = "";
heightInputBox.className = "";
weightInputBox.className = "";
console.log(heightInputBox.getAttribute('class'));
///get user input from input box "boxHeight" by using value property,
//which return user input as a string
//step1.1:get height input and convert height to a number
var height = heightInputBox.value;
height = parseFloat(height);
//step1.2:get weight input and convert weight to a number
var weight = weightInputBox.value;
weight = parseFloat(weight);
var valid = true;
if (isNaN(height)||height <0) {
alert("Invalid input for height, enter a non-negative number.");
heightInputBox.className = "error";
valid = false;
}
if (isNaN(weight)||weight <0) {
alert("Invalid input for weight, enter a non-negative number.");
weightInputBox.setAttribute('class', "error");
valid = false;
}
if (valid) //calculate BMI
{
outputBMI[0].textContent ="Your BMI is: " + (703 * weight / (height*height)).toFixed(1);
if (outputBMI[0]<18.5) outputBMI[0].textContent = "Your BMI indicates that you are underweight.";
if (outputBMI[0]>=18.5 && outputBMI[0]<=24.99) document.getElementById("result").value = "Normal";
if (outputBMI[0]>=25 && outputBMI[0]<=29.99) document.getElementById("result").value = "Obese";
if (outputBMI[0]>30) document.getElementById("result").value = "Overweight";
}
};
//add js code here to handler click event, and make the height input box be focused after the page is opened in web browser
document.getElementById('calculate').onclick = processEntries;
</script>
</body>
</html>
Here is my CSS code also, if you need it:
article, aside, figure, footer, header, main, nav, section {
display: block;
}
body {
font-family: Arial, Helvetica, sans-serif;
background: url('BMI.jpg') center center fixed;
margin: 0 auto;
width: 600px;
border: 3px solid blue;
}
html {
background-color: #eee;
}
main {
padding: 0 2em 1em;
margin: 2em;
background-color: white;
}
h2 {
color: blue;
}
label {
float: left;
width: 12em;
text-align: right;
padding-bottom: .5em;
}
div {
width: 24em;
text-align: left;
padding-bottom: .5em;
font-size: 20px;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: #FFFF00;
border: 2px solid #fe9772;
}
There's a lot to rework on your code. But the bottom line is that you need to remember that a classSelector (in your case results) always return an array. Switch to an Id if you're using an unique dom
var processEntries = function() {
var heightInputBox = document.getElementById("boxHeight");
var weightInputBox = document.getElementById("boxWeight");
var resultElm = document.getElementById("result");
resultElm.textContent = "";
heightInputBox.className = "";
weightInputBox.className = "";
console.log(heightInputBox.getAttribute('class'));
///get user input from input box "boxHeight" by using value property,
//which return user input as a string
//step1.1:get height input and convert height to a number
var height = heightInputBox.value;
height = parseFloat(height);
//step1.2:get weight input and convert weight to a number
var weight = weightInputBox.value;
weight = parseFloat(weight);
var valid = true;
if (isNaN(height)||height <0) {
alert("Invalid input for height, enter a non-negative number.");
heightInputBox.className = "error";
valid = false;
}
if (isNaN(weight)||weight <0) {
alert("Invalid input for weight, enter a non-negative number.");
weightInputBox.setAttribute('class', "error");
valid = false;
}
var bmi = 703 * weight / (height** 2)
if (valid) //calculate BMI
{
resultElm.textContent ="Your BMI is: " + (bmi).toFixed(1);
if (bmi<18.5) resultElm.textContent += " Your BMI indicates that you are underweight.";
if (bmi>=18.5 && bmi<=25) resultElm.textContent += " Your BMI indicates that you are Normal.";
if (bmi>=25 && bmi<=30)resultElm.textContent += " Your BMI indicates that you are Obese.";
if (bmi>30) resultElm.textContent += " Your BMI indicates that you are Overweight";
}
};
//add js code here to handler click event, and make the height input box be focused after the page is opened in web browser
document.getElementById('calculate').onclick = processEntries;
article, aside, figure, footer, header, main, nav, section {
display: block;
}
body {
font-family: Arial, Helvetica, sans-serif;
background: url('BMI.jpg') center center fixed;
margin: 0 auto;
width: 600px;
border: 3px solid blue;
}
html {
background-color: #eee;
}
main {
padding: 0 2em 1em;
margin: 2em;
background-color: white;
}
h2 {
color: blue;
}
label {
float: left;
width: 12em;
text-align: right;
padding-bottom: .5em;
}
div {
width: 24em;
text-align: left;
padding-bottom: .5em;
font-size: 20px;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: #FFFF00;
border: 2px solid #fe9772;
}
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight'/><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight'/><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
<div id="result"></div>
</main>
After a while, I have edited my code several times and this is a version that I think is worth sharing. I know that there are still quite some edits to do - but here it is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BMI Calculation</title>
<link rel="stylesheet" href="bmi.css">
</head>
<body>
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight'/><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight'/><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
<div class="results"></div>
</main>
<script>
var processEntries = function() {
var heightInputBox = document.getElementById("boxHeight");
var weightInputBox = document.getElementById("boxWeight");
var outputBMI = document.querySelectorAll("div.results");
outputBMI[0].textContent = "";
heightInputBox.className = "";
weightInputBox.className = "";
console.log(heightInputBox.getAttribute('class'));
var height = heightInputBox.value;
height = parseFloat(height);
var weight = weightInputBox.value;
weight = parseFloat(weight);
var valid = true;
if (isNaN(height)||height <0 || height != parseInt(height, 10)) {
outputBMI[0].textContent +=" Invalid input for height, enter a non-negative number.";
heightInputBox.className = "error";
valid = false;
}
if (isNaN(weight)||weight <0 || weight != parseInt(weight, 10)) {
outputBMI[0].textContent +=" Invalid input for weight, enter a non-negative number.";
weightInputBox.setAttribute('class', "error");
valid = false;
}
if (valid)
{
outputBMI[0].textContent ="Your BMI is: " + (703 * weight / (height*height)).toFixed(1);
//This is just for my trial and learning process. =)
var bmi = (703 * weight / (height*height)).toFixed(1);
if (bmi<18.5) outputBMI[0].textContent += " Your BMI indicates that you are underweight.";
if (bmi>=18.5 && bmi<=25) outputBMI[0].textContent += "Your BMI indicates that you are normal.";
if (bmi>25 && bmi<=30) outputBMI[0].textContent += "Your BMI indicates that you are obsese.";
if (bmi>30) outputBMI[0].textContent += "Your BMI indicates that you are overweight.";
}
};
//handler button click event
document.getElementById('calculate').onclick = processEntries;
</script>
</body>
</html>
I know this question already has a good and valid answer.
The following is simply the result of me playing around with the fiddle, trying to shorten it and make it more "responsive".
I removed the calculate button and use eval() now to tolerantly convert and calculate the input fields' values.
const qs=s=>document.querySelector(s);
evl=s=>{var v='', el=qs(s);
try{v=eval(el.value)||''} catch(er){v=''}
el.nextElementSibling.innerText=(v?'='+v.toFixed(2):v);
return v
}
var scale=[[18.5,"underweight"],
[25,"normal"],[30,"obese"],
[31,"seriously overweight"]];
qs("body").addEventListener("keyup",ev=>{if(ev.target.type!='text') return;
var txt, height=evl("#boxHeight"), weight=evl("#boxWeight");
if (height>0 && weight>0){
BMI=703*weight/(height*height);
scale.every(sc=>(txt=sc[1],BMI>sc[0]));
txt='Your BMI of '+BMI.toFixed(1)+" indicates<br>that you are "+txt+".";
} else txt='';
qs("#result").innerHTML=txt
});
body {
font-family: Arial, Helvetica, sans-serif;
background: url('BMI.jpg') center center fixed;
margin: 0 auto;
width: 600px;
border: 3px solid blue;
}
html {
background-color: #eee;
}
main {
padding: 0 2em 1em;
margin: 2em;
background-color: white;
}
h2 {
color: blue;
}
label {
float: left;
width: 12em;
text-align: right;
padding-bottom: .5em;
}
div {
width: 24em;
text-align: left;
padding-bottom: .5em;
font-size: 20px;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
span {margin-left:20px;
font-size:1.5ex;}
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight' placeholder="value or formula"/><span id="one"></span><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight' placeholder="value or formula"/><span id="two"></span><br>
<div id="result"></div>
</main>
I'm building a form that takes input including a few texareas and outputs what was input into those fields on the same page below the form. It works great, except when I paste a multi-line code snippet in any of the textareas, the output does not look like what I pasted originally.
How can I prevent code in my #results div from being styled?
Here is a screenshot showing the output of texarea elements being mis-aligned, and mis-formatted. Everything from the "FILE" to "TAGS" heading displays and is formatted correctly.
I had trouble finding the right long-tail term to Google on for this. Perhaps someone can tell me what the correct term is for this kind of
output produced from self-submitting form?
My Code:
submit.onclick = function() {
// build html output
document.querySelectorAll('input, textarea').value = "";
var out = "";
//var form = document.querySelector('form');
var outPartsArr = [];
/* GATHER FORM VALUES */
var filename = document.querySelector('#filename').value;
var dateCreated = document.querySelector('#date-created').value;
var dateModified = document.querySelector('#date-modified').value;
var postURL = document.querySelector('#post-url').value;
var postTitle = document.querySelector('#post-title').value;
var postTags = document.querySelector('#post-tags').value;
var postContent = document.querySelector('#post-content').value;
/* GET TIME */
// from: https://www.codexworld.com/how-to/get-current-date-time-using-javascript/
var today = new Date();
var yy = today.getFullYear().toString().substr(-2);
var mm = today.getMonth()+1;
var dd = today.getDate() < 10 ? "0" + today.getDate() : today.getDate() ;
var date = mm + "/" + dd + "/" + yy;
var hh = today.getHours() > 12 ? today.getHours() - 12 : today.getHours();
var mm = today.getMinutes();
var time = hh + ":" + mm;
/* BUILD OUTPUT */
var filenameOut = "<span class='line-title'>FILE: </span>" + filename + "<br>";
var dateCreatedOut = "<span class='line-title'>DATE CREATED: </span>" + dateCreated + "<br>";
var dateModifiedOut = "<span class='line-title'>DATE MODIFIED: </span>" + dateModified + "<br>";
var postURLOut = "<span class='line-title'>URL: </span>" + postURL + "<br>";
var postTitleOut = "<span class='line-title'>TITLE: </span>" + postTitle + "<br>";
var postTagsOut = "<span class='line-title'>TAGS: </span>" + postTags + "<br>";
var postContentOut = "<span class='line-title'>CONTENT: </span>" + "<pre>" + postContent + "</pre><br>";
// Add each line item html snippet to array
outPartsArr.push(filenameOut, dateCreatedOut, dateModifiedOut, postURLOut, postTitleOut, postTagsOut, postContentOut);
console.log("%c postContent ","background:orange");
console.log(postContent);
out += "<ul class='row-lines'>"
// loop through out parts array and wrap each in <li> tags
// while building the out string
outPartsArr.forEach(function(part, i) {
out += "\t<li>" + part + "</li>";
});
out += "</ul>";
console.log("%c out ","background:orange");
console.log(out);
// display in results div
document.querySelector('#results').innerHTML = out;
// #GOTCHA --> Without this return statement output appears for a milisecond
// then the form refreshes.
return false;
};
* {
box-sizing: border-box;
}
body {
width: 100%;
}
#wrapper {
max-width: 1024px;
width: 80%;
border: solid gray 1px;
margin: 2em auto;
padding: 1.2em
}
form {
border: solid red 2px;
background: aliceblue;
margin-bottom: 1.5em;
padding: .6em;
}
form label {
margin-right: 0;
padding-right: 0;
width: 200px;
float: left;
font-family: Arial, Tahoma, sans-serif;
font-weight: bold;
}
form input {
padding: .4em .6em;
margin-bottom: .4em;
width: 80%;
}
form input[type="submit"] {
background: green;
color: white;
margin-top: 1em;
width: 6em;
border-radius: .3em;
margin-left: 0;
}
textarea {
width: 80%;
height: 10em;
/*resize: both;*/
border-radius: 5px;
border: 1px solid #ccc;
box-shadow: 1px 1px 1px #999;
}
/* OUTPUT */
#results {
padding: 2em .6em;
background: #ffffb3;
border: solid brown 1px;
}
#results h3 {
font-family: Arial, Tahoma, sans-serif;
color: brown;
}
.line-title {
font-weight: bold;
float: left;
width: 10em;
color: brown;
font-family: Arial, Tahoma, sans-serif;
line-height: 1.2em;
}
.row-lines li {
line-height: 2em;
list-style: none;
}
<div id="wrapper">
<header class="content">
<h1>Eric Hepperle's Stack Overflow Post Builder (2018)</h1>
<p>Some header tag line or other introductory text.</p>
</header>
<main>
<form id="stack-post-builder" method="GET" action="#">
<label for="filename">FILE:</label>
<input type="text" id="filename" name="filename" value="" ><br>
<label for="date-created">DATE CREATED:</label>
<input type="text" id="date-created" name="date-created" value=""><br>
<label for="date-modified">DATE MODIFIED:</label>
<input type="text" id="date-modified" name="date-modified" value=""><br>
<label for="post-url">URL:</label>
<input type="text" id="post-url" name="post-url" value="" ><br>
<label for="post-title">TITLE:</label>
<input type="text" id="post-title" name="post-title" value="" ><br>
<label for="post-tags">TAGS:</label>
<textarea id="post-tags" name="post-tags" placeholder="Enter post tags"></textarea><br>
<label for="post-content">CONTENT:</label>
<textarea id="post-content" name="post-content" placeholder="Enter post tags"></textarea><br>
<!-- <input type="submit" id="stack-post-builder-submit" name="stack-post-builder-submit" value="Submit"> -->
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<section id="results">Results will show up here.</section>
</main>
</div><!-- END wrapper div -->
I have this calculator that I'd like for the results to auto update after the the user adds input.
I've tried the .keyup thing, but I don't understand it.
I'm kinda new to javascript.
Here's my codepen for the project.
http://codepen.io/Tristangre97/pen/zNvQON?editors=0010
HTML
<div class="card">
<div class="title">Input</div>
<br>
<div id="metalSpan"><input class="whiteinput" id="numMetal" type="number">
<div class="floater">Metal Quantity</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan"><input class="whiteinput" id="numForge" type=
"number">
<div class="floater">Forge Quantity</div></div>
<br>
<input checked id="rb1" name="fuel" type="radio" value="spark"> <label for=
"rb1">Sparkpowder</label> <input id="rb2" name="fuel" type="radio" value=
"wood"> <label for="rb2">Wood</label><br>
<br>
<button class="actionButton" id="submit" type="button">Calculate</button></div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div>
<br>
<div id="result"><span id="spreadMetal"></span> metal <span class=
"plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class=
"plural"></span> forge <span id="allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br></div>
</div>
</div>
JS
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("#submit").click(function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == '') {
$("#metalAlert").html("Please enter a value");
}
else if (forges == 0 || forges == '') {
$("#metalAlert").html('');
$("#forgeAlert").html("Please enter a value");
}
else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
}
else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
}
else {
$(".plural").html("in the");
}
$("#forgeAlert").html('');
if (metals % 2 == 0) {}
else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(((spread / 2) * 20) / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
}
else {
$("#allSpark").html(String(''));
}
$("#timeSpark").html(String((isWood) ? (sparks / 2) : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html((isWood) ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
To run the function whenever something is inputted in the field, try the
$("input").on('input', function() { .. });
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("input").on('input', function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == "") {
$("#metalAlert").html("Please enter a value");
} else if (forges == 0 || forges == "") {
$("#metalAlert").html("");
$("#forgeAlert").html("Please enter a value");
} else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
} else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
} else {
$(".plural").html("in the");
}
$("#forgeAlert").html("");
if (metals % 2 == 0) {
} else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(spread / 2 * 20 / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
} else {
$("#allSpark").html(String(""));
}
$("#timeSpark").html(String(isWood ? sparks / 2 : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html(isWood ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
body {
background-color:#316b6f;
font-family:Helvetica,sans-serif;
font-size:16px;
}
.whiteinput {
outline: none;
border-width: 0px;
margin: 0;
padding: .5em .6em;
border-radius: 2px;
font-size: 1em;
color: #316b6f;
}
.actionButton {
background-color: #316B6F;
color: #fff;
padding: .5em .6em;
border-radius: 3px;
border-width: 0px;
font-size: 1em;
cursor: pointer;
text-decoration: none;
-webkit-transition: all 250ms;
transition: all 250ms;
}
.actionButton:hover {
color: #fff;
}
.actionButton:active {
background: #BBFF77;
color: #316B6F;
-webkit-transition: all 550ms;
transition: all 550ms;
}
.card {
position: relative;
background: #4E8083;
color:#FFFFFF;
border-radius:3px;
padding:1.5em;
margin-bottom: 3px;
}
.title {
background: #76B167;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.title2 {
background: #2F3A54;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.floater {
padding: 3px;
}
.radiobtn {
background: red;
border-radius: 2px;
}
input[type=radio] + label:before {
content: "";
display: inline-block;
width: 20px;
height: 20px;
vertical-align:middle;
margin-right: 8px;
background-color: #aaa;
margin-bottom: 6px;
border-radius: 2px;
-webkit-transition: all 450ms;
transition: all 450ms;
}
input[type=radio], input[type=checkbox] {
display:none;
}
input[type=radio]:checked + label:before {
content: "\2022"; /* Bullet */
color:white;
background-color: #fff;
font-size:1.8em;
text-align:center;
line-height:14px;
margin-right: 8px;
}
input[type=checkbox]:checked + label:before {
content:"\2714";
color:white;
background-color: #fff;
text-align:center;
line-height:15px;
}
*:focus {
outline: none;
}
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="card">
<div class="title">Input</div><br>
<div id="metalSpan">
<input class="whiteinput" id="numMetal" type="number">
<div class="floater">
Metal Quantity
</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan">
<input class="whiteinput" id="numForge" type="number">
<div class="floater">
Forge Quantity
</div>
</div>
<br>
<input type="radio" id="rb1" name="fuel" value="spark" checked>
<label for="rb1">Sparkpowder</label>
<input type="radio" id="rb2" name="fuel" value="wood">
<label for="rb2">Wood</label><br><br>
<button class="actionButton" id="submit"
type="button">Calculate</button>
</div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div><br>
<div id="result">
<span id="spreadMetal"></span> metal <span class="plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class="plural"></span> forge <span id=
"allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br>
</div>
</div>
</div>
Codepen
It is triggering your errors because that is part of your function.
More info regarding the input method.
Look, you have two options:
Put all your algorithm of submit click into a function and call him into two binds: the submit click and input change (on('change')) or just remove your calculate button and rely the calculation into onchange of the inputs: each change of checks or inputs will trigger the calculation of metals. The second approach it's more interesting for me and removes the necessity to the user clicks to calculate (he already clicked into inputs and checks). Obviously you can add a filter to only allow to calculation function run after a certain minimum number of data filled, it's a good idea to avoid poor results resulted by lack of data.
In order to auto update calculation, we have to listen to users input on input elements. The easiest approach with minimum changes to existing code is to add input events and emit click on the button:
$("#numMetal, #numForge").on('input', function(){
$("#submit").click()
})
Better approach is to move calculation logic to separate function and call it on desirable events:
$("#numMetal, #numForge").on('input', function(){
calculate()
})
$("#submit").click(function(){
calculate()
})
This will keep the code structured and easier to follow.
Try this:
$( "#numMetal, #numForge" ).keyup(function(event) {
console.log('a key has been pressed');
// add code to handle inputs here
});
What happens here is that an event listener - the key up event - is bound to the two inputs you have on your page. When that happens the code inside will be run.
As suggested in other comments it would be a good idea to call a separate method with all the input processing code you have in the submit call, this way you will avoid code duplication.
You will also want to bind events to the checkboxs. This can be achieved with this:
$( "input[name=fuel]" ).on('change',function() {
console.log('checkbox change');
// call processing method here
});
I wanted to create a Cash Register Effect using Pure Javascript(With out using any libraries),
Here is the link for Cash register Effect which is implemented Using Mootools,
http://jsbin.com/ehuzes/edit#preview
I want to get this effect using raw Javascript. It will be huge help, If somebody gives the solution.
$('#number').on('change', function (e) {
$(this).cashregister($(this).val());
});
(function ($) {
$.fn.cashregister = function (num) {
var output = $('#output').html();
function intervalfunc(interval, num) {
var end = parseInt($('#number').html());
var cont = parseInt($('#output').html())
$('#output').html( cont + interval );
if ( $('#output').html() == num ) {
clearInterval(int);
return false;
}
}
if (num > output) {
var int = setInterval(function() { intervalfunc(1, num) }, 0.1);
}else if (num < output) {
var int = setInterval(function() { intervalfunc(-1, num) }, 0.1);
}else if (num == $('#output').html() ) {
// do nothing
}else{
alert("Invalid Input!");
}
};
})(jQuery);
http://jsfiddle.net/DuLjC/3/ -> working version of suggested fix
use an onclick function on a button or something, which should get the number (value from maybe a text box) and to send that variable to a defined function which uses .innerHTML on a div to change the number value, then you use SetInterval function to make the number go either up or down by 1 each interval. then use clearInterval when the number has been reached.
maybe something like:
<div id = "container">0</div>
<input type = 'text'
id = 'number' />
<input type = 'button'
value = 'change amount'
onclick = "var num = document.getElementById('number').value;
cashregister(num);" />
for the HTML and:
<script type = "text/javascript">
function cashregister(num) {
var cont = document.getElementById('container').innerHTML;
if (num < cont) {
var int = setInterval("intervalfunc(1)", (interval_time_in_miliseconds));
function intervalfunc(num) {
var end = document.getElementById('number');
var cont = document.getElementById('cont').innerHTML;
cont.innerHTML = cont + num;
if (cont == end) {
clearInterval(int);
}
}
} else if (num > cont) {
var int = setInterval("intervalfunc(-1)", (interval_time_in_miliseconds));
function intervalfunc(num) {
var end = document.getElementById('number');
var cont = document.getElementById('cont').innerHTML;
cont.innerHTML = cont + num;
if (cont == end) {
clearInterval(int);
}
}
} else if (num == cont) {
//do nothing
} else {
alert("invalid input!");
}
}
</script>
I'm not sure if this exact code will work but what you want is something along these lines.
I like this one by Nevan Scott: https://codepen.io/nevan/pen/uBkEr
var total = 0;
document.getElementById('entry').onsubmit = enter;
function enter() {
var entry = document.getElementById('newEntry').value;
var entry = parseFloat(entry);
currency = currencyFormat(entry);
document.getElementById('entries').innerHTML += '<tr><td></td><td>' + currency + '</td></tr>';
total += entry;
document.getElementById('total').innerHTML = currencyFormat(total);
document.getElementById('newEntry').value = '';
return false;
}
function currencyFormat(number) {
var currency = parseFloat(number);
currency = currency.toFixed(2);
currency = '$' + currency;
return currency;
}
body {
background: #EEE;
font-family: sans-serif;
font-size: 20px;
margin: 3em;
padding: 0;
}
#register {
width: 20em;
margin: auto;
}
#ticket {
background: white;
margin: 0 1em;
padding: 1em;
box-shadow: 0 0 5px rgba(0,0,0,.25);
}
#ticket h1 {
text-align: center;
}
#ticket table {
font-family: monospace;
width: 100%;
border-collapse: collapse;
}
#ticket td, #ticket th {
padding: 5px;
}
#ticket th {
text-align: left;
}
#ticket td, #ticket #total {
text-align: right;
}
#ticket tfoot th {
border-top: 1px solid black;
}
#entry {
background: #333;
padding: 12px;
border-radius: 10px;
box-shadow: 0 0 5px rgba(0,0,0,.25);
}
#entry input {
width: 100%;
padding: 10px;
border: 1px solid black;
text-align: right;
font-family: sans-serif;
font-size: 20px;
box-shadow: inset 0 0 3px rgba(0,0,0,.5);
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#entry input:focus {
outline: none;
border-color: rgba(255,255,255,.75);
}
<div id="register">
<div id="ticket">
<h1>Thank You!</h1>
<table>
<tbody id="entries">
</tbody>
<tfoot>
<tr>
<th>Total</th>
<th id="total">$0.00</th>
</tr>
</tfoot>
</table>
</div>
<form id="entry">
<input id="newEntry" autofocus placeholder="How Much?">
</form>
</div>