Quantity in Inches to Convert to Feet, Centimeters or Yards Javascript - javascript

The instructions goes as follows:
Ask the user to enter a quantity in inches (in a textbox).
Have a select box with options for: Feet, Centimeters, Yards.
If they chose inches, calculate the conversion as 1 inch = 0.0833 feet. For Centimeters: 1 inch = 2.54 centimeters. For Yards, 1 inch = 0.02778.
Because the user may enter a decimal amoung (e.g. 3.99), be sure to parse using the parseFloat option.
Using a reference: Look up the toFixed() function and make sure that your result is outputted to 2 decimal places.
Output to a div section called results. Output using the innerHTML command.
This is the code that I currently have in place
function convertCurrency(r) {
document.getElementById("cnvrtMoney").innerHTML = "output";
if (dropdown == "feetConversion".parseFloat(r)) {
Convert = Convert / 0.0833;
} else if (dropdown == "centimetersConversion".parseFloat(r)) {
Convert = Convert / 2.54;
} else if (dropdown == "yardsConversion".parseFloat(r)) {
Convert = Convert / 0.02778;
}
Convert = Convert.toFixed(2);
var resultsString = "The amount would be" + Convert;
document.getElementById('results').innerHTML = resultsString;
}
body {
background-color: gray;
}
#heading {
background-color: lightgray;
text-align: center;
}
#formConverter {
background-color: white;
text-align: center;
text-justify: auto;
}
#EndResults {
background-color: darkgray;
text-align: center;
}
<html>
<head>
<meta charset="utf-8">
<title>Assignment 01: Currency Converter</title>
</head>
<body>
<div id="heading">
<h1> Currency Converter </h1>
<img src="CurrencyConverter.jpg" alt="Currency Converter Banner" width="600" height="200">
</div>
<div id="formConverter">
<form action="CurrencyConverter.php" method="get">
Enter Quantity (In Inches): <input type="text" name="inputInches" /><br> Select Conversion:
<select name="dropdown">
<option value="feetConversion">Feet </option>
<option value="centimetersConversion">Centimeters </option>
<option value="yardsConversion">Yards </option>
</select>
</form>
</div>
<div id="results">
</div>
</body>
</html>
I'm trying to make it display once the user clicks on the dropdown button with the exact conversion that it needs to be. If anyone could help I would greatly appreciate it.

First, this is JavaScript code, you do not need <form>.
Second, to access elements by ID you have to set ID attribute instead of NAME.
Third, math is wrong.
Forth...
It's better to show working code. This is event handler:
function convertCurrency() {
var dropdown = document.getElementById("dropdown").value;
var inputInches = document.getElementById("inputInches").value;
switch (dropdown){
case "feetConversion":
Convert = inputInches * 0.0833;
break;
case "centimetersConversion":
Convert = inputInches * 2.54;
break;
case "yardsConversion":
Convert = inputInches * 0.02778;
break;
}
var resultsString = "The amount would be: " + Convert;
document.getElementById("results").innerHTML = resultsString;
}
This is HTML layout:
<input type="text" id="inputInches"/><br>
Select Conversion:
<select id="dropdown" onchange="convertCurrency()">
<option value="" disabled="disabled" selected="selected"></option>
<option value="feetConversion">Feet </option>
<option value="centimetersConversion">Centimeters </option>
<option value="yardsConversion">Yards </option>
</select>
<div id="results"></div>
http://jsfiddle.net/ArtyomShegeda/xbj5pf62/13/

You never call convertCurrency. You need an event listener that calls it. You could put a "Convert" button in the form, and call it when they click on the button.
Code like if (dropdown == "feetConversion".parseFloat(r)) makes no sense. parseFloat() is a global function, it's not a method of a string. You just want to compare dropdown to the string. parseFloat should be used to set the Convert variable at the beginning of the function.
You don't need an action or method in a form that's being processed in JavaScript, not the server.
You never set the value of dropdown. You need to get that from the value of the dropdown. I added an ID to it, and get that using document.getElementById("selectConversion").value
There's no element cnvrtMoney. I'm not sure what the point of document.getElementById("cnvrtMoney").innerHTML = "output"; is supposed to be. I've removed it.
Your conversions are all wrong, you're dividing when you should be multiplying.
function convertCurrency(r) {
var dropdown = document.getElementById("selectConversion").value;
var Convert = parseFloat(r);
if (dropdown == "feetConversion") {
Convert = Convert / 12;
} else if (dropdown == "centimetersConversion") {
Convert = Convert * 2.54;
} else if (dropdown == "yardsConversion") {
Convert = Convert / 36;
}
Convert = Convert.toFixed(2);
var resultsString = "The amount would be " + Convert;
document.getElementById('results').innerHTML = resultsString;
}
document.getElementById("convertButton").addEventListener("click", function() {
convertCurrency(document.getElementById("inputInches").value);
});
body {
background-color: gray;
}
#heading {
background-color: lightgray;
text-align: center;
}
#formConverter {
background-color: white;
text-align: center;
text-justify: auto;
}
#EndResults {
background-color: darkgray;
text-align: center;
}
<html>
<head>
<meta charset="utf-8">
<title>Assignment 01: Currency Converter</title>
</head>
<body>
<div id="heading">
<h1> Currency Converter </h1>
<img src="CurrencyConverter.jpg" alt="Currency Converter Banner" width="600" height="200">
</div>
<div id="formConverter">
<form>
Enter Quantity (In Inches): <input type="text" name="inputInches" id="inputInches" /><br> Select Conversion:
<select name="dropdown" id="selectConversion">
<option value="feetConversion">Feet </option>
<option value="centimetersConversion">Centimeters </option>
<option value="yardsConversion">Yards </option>
</select>
<br>
<input type="button" value="Convert" id="convertButton">
</form>
</div>
<div id="results">
</div>
</body>
</html>

Ok, I had to rewrite the entire thing, but here it is
function convertCurrency(r) {
let c = document.getElementById('q').value;
let v = document.getElementById('c').value;
switch(v){
case "feet":
result = c / 0.0833;
break;
case "cent":
result = c / 2.54;
break;
case "yard":
result = c /0.02778;
break;
}
result = result.toFixed(2);
var resultsString = "The amount would be " + result;
document.getElementById('results').innerHTML = resultsString;
}
body {
background-color: gray;
}
#heading {
background-color: lightgray;
text-align: center;
}
#formConverter{
background-color: white;
text-align: center;
text-justify:auto;
}
#results{
background-color:darkgray;
text-align: center;
}
<div id="heading">
<h1> Currency Converter </h1>
<img src="CurrencyConverter.jpg" alt="Currency Converter Banner" width="600" height="200">
</div>
<div id="formConverter">
<p>
Enter Quantity (in inches):
<input type="number" id="q" name="q">
</p>
<p>
Select conversion:
<select id="c" name="c">
<option value="feet">Feet</option>
<option value="cent">Centimeters</option>
<option value="yard">Yards</option>
</select>
</p>
<button onclick="convertCurrency()">
Convert
</button>
</div>
<div id="results">
</div>

There's a lot needing to be fixed here, but changing the contents of your script tag to the following should work:
<script>
window.onload = function() {
var form = document.getElementById( "convert-input" );
form.getElementsByTagName( "select" )[ 0 ].addEventListener( "input", function(){
convertCurrency( this.value, form.getElementsByTagName( "input" )[ 0 ].value );
}, true );
}
function convertCurrency( dropdown, r) {
if (dropdown == "feetConversion"){
Convert = parseFloat(r) * 0.0833;
}
else if (dropdown == "centimetersConversion"){
Convert = parseFloat(r) * 2.54;
}
else if (dropdown == "yardsConversion"){
Convert = parseFloat(r) * 0.02778;
}
Convert = Convert.toFixed(2);
var resultsString = "The amount would be " + Convert;
document.getElementById('results').innerHTML = resultsString;
}
</script>
Note that your conversions were incorrect as you had chosen a scaling factor that needed multiplication

Related

call a function from another function increment the number of times for number entered then place an ' !' to every output that is even

I am trying to create a loop. so far I can get it to say Hello Tom and just the number. I want to add on a function named addOrderListItems that receives the name and numOfTimes as parameters. Then call the addOrderListItems function from the displayHello function and if the number is even add an !
so if I type name Braden and numOfTimes 8
the output will display a list
1.Hello Braden
2.Hello Braden!
3.Hello Braden
4.Hello Braden!
5.Hello Braden
6.Hello Braden!
7.Hello Braden
8.Hello Braden!
9.Hello Braden
function displayHello() {
let name = document.getElementById("helloNameInput").value,
numOfTimes = document.getElementById("numOfTimesInput").value;
}
function addOrderListItems() {
let numOfTimes = 0;
while (numOfTimes > 0 ) {
document.getElementById("helloNameOutput").innerHTML = "Hello " + name + numOfTimes;
numOfTimes++;
}
}
function clearName() {
document.getElementById("helloNameInput").value = "";
document.getElementById("numOfTimesInput").value = "";
document.getElementById("helloNameOutput").innerText = "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript: Looping Structures Assignment</title>
<link href="/bootstrap.min.css" rel="stylesheet" />
</head>
<body class="p-3">
<h1>JavaScript: Looping Structures Assignment</h1>
<!--Name input-->
<div class="mb-3">
<label for="helloNameInput" class="form-label">Name:</label>
<input
type="text"
class="form-control"
name="helloNameInput"
id="helloNameInput"
placeholder="Enter a name"
/>
</div>
<!--Number of Times input-->
<div class="mb-3">
<label for="numOfTimesInput" class="form-label">Number of Times:</label>
<input
type="text"
class="form-control"
name="numOfTimesInput"
id="numOfTimesInput"
placeholder="Enter number"
/>
</div>
<!--Name output-->
<ol id="helloNameOutput"></ol>
<!--Display Hello! & Reset buttons-->
<div>
<button class="btn btn-primary" id="displayHelloButton" onclick="displayHello();" >
Display Hello!
</button>
<button class="btn btn-danger" id="clearButton" onclick=" clearName();">Clear</button>
</div>
<script src="/script.js"></script>
</body>
</html>
```
You'll probably need a few functions to help you accomplish your goal and keep your code organized. Below I've created an example in a code snippet to demonstrate how the functionality you described can be implemented. I've included lots of comments to explain and help you understand the steps involved.
You can search on MDN and read the JavaScript documentation if there are parts you've never seen or don't yet understand — for example, here are a few links to some of the DOM APIs used:
Document.createElement()
Element.remove()
Node.firstChild
Node.appendChild()
Keep learning, and good luck in your programming!
const nameInput = document.getElementById('helloNameInput');
const qtyInput = document.getElementById('numOfTimesInput');
const btn = document.getElementById('writeGreeting');
const output = document.getElementById('helloNameOutput');
function createGreetingText (name, withExclamationPoint) {
return `Hello ${name}${withExclamationPoint ? '!' : ''}`;
}
function createGreetingListItem (name, withExclamationPoint) {
const listItem = document.createElement('li');
listItem.textContent = createGreetingText(name, withExclamationPoint);
return listItem;
}
function clearOutput () {
// Delete every child element from the output element:
while (output.firstChild) {
output.firstChild.remove();
}
}
function writeGreeting () {
// Get the trimmed input value (or use "world" if it's empty):
const name = nameInput.value.trim() || 'world';
// Get the number of times (quantity) from the other input:
let qty = parseInt(qtyInput.value);
// If the number input value couldn't be parsed as a valid integer,
// use 1 as the default valid value and update the input:
if (!Number.isInteger(qty)) {
qty = 1;
qtyInput.value = 1;
}
clearOutput();
// Loop the number of times:
for (let i = 1; i <= qty; i += 1) {
// Create and append a list item element each time:
const isEven = i % 2 === 0;
const listItem = createGreetingListItem(name, isEven);
output.appendChild(listItem);
}
}
// Bind the "writeGreeting" function to the button's "click" event,
// so that it runs each time the button is clicked:
btn.addEventListener('click', writeGreeting);
#container {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 1rem;
font-family: sans-serif;
}
button, input {
font-size: 1rem;
padding: 0.5rem;
}
<div id="container">
<input
type="text"
id="helloNameInput"
placeholder="name"
value="Braden"
/>
<input
type="number"
step="1"
min="1"
id="numOfTimesInput"
placeholder="# of times"
value="8"
/>
<button id="writeGreeting">Write greeting</button>
<ol id="helloNameOutput"></ol>
</div>

JavaScript - Flawed Calculator Using Google as Example

As you can see on Google conversion at: Here
When you click the second drop down box and choose meters, Instead of it staying at 12 meters, it converts to .3048 meters, which isn't what I want. I want it so that when you change to meters on the right drop down box, it stays as 12 meters and the box on the left updates to 39.3701 feet. Here is my code so far.
var units = [['Inches', 0.025400000000000], ['Feet', 0.30480000000000000], ['Furlongs', 201.168], ['Meters', 1.00]];
var selectors = document.querySelectorAll('.newClass1');
for (var i = 0; i < units.length; i++) {
for (var j = 0; j < selectors.length; j++) {
var option = document.createElement('option');
option.value = units[i][1];
option.textContent = units[i][0];
selectors[j].add(option);
}
}
function calcLength1() {
var SpecialValue = parseFloat(document.getElementById("lengthInput1").value) * parseFloat(document.getElementById("lengthCalc1").value) / parseFloat(document.getElementById("lengthCalc2").value);
document.getElementById("lengthInput2").value = SpecialValue;
}
function calcLength2() {
var SpecialValue = parseFloat(document.getElementById("lengthInput2").value) * parseFloat(document.getElementById("lengthCalc2").value) / parseFloat(document.getElementById("lengthCalc1").value);
document.getElementById("lengthInput1").value = SpecialValue;
}
Here is my HTML:
<div class="panel">
<p>From:</p>
<select style="float:left" id="lengthCalc1" class="js-example-basic-single select2-container newClass1" oninput="calcLength2()" onchange="calcLength2()">
</select>
<input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="lengthInput1" type="number" oninput="calcLength1()" />
<p>To:</p>
<select style="float:left" id="lengthCalc2" class="js-example-basic-single select2-container newClass1" oninput="calcLength1()" onchange="calcLength1()">
</select>
<input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="lengthInput2" type="number" oninput="calcLength2()" onchange="calcLength2()" />
</div>
It's completely flawed. Please help me make a good calculator.
Update: To make the converter function properly same as the google length converter, you can try the following:
Update the second input box value when either of the of the dropdown of units changes.
Update the first input box when the second input box is changed, and vice-versa.
This means, your first input box value will update only when the user changes the value of the second input. Try it on the google's converter, it behaves the same way.
Use the following code to make it work.
var units = [
['Inches', 0.025400000000000],
['Feet', 0.30480000000000000],
['Furlongs', 201.168],
['Meters', 1.00]
];
var selectors = document.querySelectorAll('.newClass1');
for (var i = 0; i < units.length; i++) {
for (var j = 0; j < selectors.length; j++) {
var option = document.createElement('option');
option.value = units[i][1];
option.textContent = units[i][0];
selectors[j].add(option);
}
}
function updateInputBox2() {
var SpecialValue = parseFloat(document.getElementById("lengthInput1").value) * parseFloat(document.getElementById("lengthCalc1").value) / parseFloat(document.getElementById("lengthCalc2").value);
document.getElementById("lengthInput2").value = SpecialValue;
}
function updateInputBox1() {
var SpecialValue = parseFloat(document.getElementById("lengthInput2").value) * parseFloat(document.getElementById("lengthCalc2").value) / parseFloat(document.getElementById("lengthCalc1").value);
document.getElementById("lengthInput1").value = SpecialValue;
}
<div class="panel">
<p>From:</p>
<select style="float:left" id="lengthCalc1" class="js-example-basic-single select2-container newClass1" oninput="updateInputBox2()" onchange="updateInputBox2()">
</select>
<input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="lengthInput1" type="number" oninput="updateInputBox2()" />
<p>To:</p>
<select style="float:left" id="lengthCalc2" class="js-example-basic-single select2-container newClass1" oninput="updateInputBox2()" onchange="updateInputBox2()">
</select>
<input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="lengthInput2" type="number" oninput="updateInputBox1()" onchange="updateInputBox1()" />
</div>
First problem with the conversion (outdated)
Convert the values to number correctly and it should work. You have few typos in your code and also there's a left hand assignment error. Look at this line in your code, there are two errors:
parseFloat(document.getElementById("lengthInput2").value) = praseFloat(SpecialValue);
Try this, it should work.
function calcLength1() {
var SpecialValue = parseFloat(document.getElementById("lengthInput1").value) * parseFloat(document.getElementById("lengthCalc1").value) / parseFloat(document.getElementById("lengthCalc2").value);
document.getElementById("lengthInput2").value = SpecialValue;
}
function calcLength2() {
var SpecialValue = parseFloat(document.getElementById("lengthInput2").value) * parseFloat(document.getElementById("lengthCalc2").value) / parseFloat(document.getElementById("lengthCalc1").value);
document.getElementById("lengthInput1").value = SpecialValue;
}

Adding labels to QR codes

I have created a QR code generator. The user can create multiple QR codes.
I would like the user to be able to name each QR code (referred to as a checkpoint) by writing the desired checkpoint name in the text input field, clicking the Assign Name button and having the text input field disappear, being replaced by the name the user typed into the field.
The user can input checkpoint names, however, it only works for the first QR code printed, and the label only appears below the QR code. Below is the code that I have so far. Any help or suggestions to help me get the ball rolling on this would be very much appreciated. Thank you!
Note: If you try to run this to see the QR codes, you will have to enter something in the text field and press generate. They won't appear automatically.
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: arial, sans-serif;
}
section {
margin: 50px auto;
max-width: 350px;
text-align: center;
}
textarea {
width: 50%;
height: 50px;
margin-bottom: 10px;
}
#size {
max-width: 64px;
}
label {
display: inline-block;
width: 140px;
text-align: left;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<section>
<h1>QR Code Generator</h1>
<p>Enter a URL or some text bellow and hit the Generate button (<kbd>Ctrl</kbd>+<kbd>Enter</kbd>)!</p>
<textarea id="textarea" autofocus></textarea>
<div class="block">
<label for="size">Size (px):</label>
<input align="left" id="size" type="number" value="150" min="50" max="500" step="50">
<label for="amount">Amount of Labels:</label>
<input align="left" id="amount" type="number" value="1" min="1" max="500" step="1">
<button id="genQRcode">Generate</button>
</div>
<div id="content" style="display: none;"></div>
</section>
<p id="demo" align="center"></p>
<script>
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<script id="template-qr-code" type="text/html">
<p> <img id="qrcode" src="{{src}}" /></p>
<label for="checkpoint"> Checkpoint Name:</label>
<input id="cpname" type="text" value="">
<button onclick="myFunction()">Assign Name</button>
</script>
<script type="text/javascript">
window.addEventListener('load', function() {
var textarea = document.getElementById("textarea"),
content = document.getElementById("content"),
amount = document.getElementById("amount"),
qrTemplate = document.getElementById('template-qr-code');
function genQRcode() {
var data = encodeURIComponent(textarea.value),
size = document.getElementById("size").value,
chart = "http://chart.googleapis.com/chart?cht=qr&chs=" + size + "x" + size + "&choe=UTF-8&chld=L|0&chl=" + data;
if (data === "") {
alert("Please enter valid data!");
textarea.focus();
content.style.display = "none";
} else {
for (var i = 0; i < amount.value; i++) {
var qrSrc = qrTemplate.innerHTML;
qrSrc = qrSrc.replace(new RegExp('{{src}}', 'g'), chart);
qrSrc = qrSrc.replace(new RegExp('{{i}}', 'g'), i);
content.insertAdjacentHTML('beforeEnd', qrSrc);
}
content.style.display = "";
}
}
document.getElementById("genQRcode").addEventListener("click", genQRcode);
document.addEventListener("keydown", function(e) {
if (e.ctrlKey && e.keyCode == 13) {
genQRcode();
}
});
});
</script>
</body>
</html>
Your click function
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
is getting and setting an element by ID. That will only ever affect a single element on the page (usually the first one that the browser runs into with that specific id). You need to use a different selector / way of getting the label you want to change because you can't reuse ids.
Basically you need to make your label fields distinct so you can actually select them

Suggestions with JavaScript operators

I am trying to make a application with JavaScript.
The app should have a plus, a minus button, and a clear button. In the middle there should be an input where a number will appear.
The app will start off with 1000 and plus will increase by 1000, the minus button will decrease it by 1000, and the clear button will reset the application. The minimum number in the app should be 1000.
I have figured out most but the plus button is not working as it should and I cannot get the app to have 1000 as minimum, it just continues into minus.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Application</title>
</head>
<style>
#application{
margin-top: 300px;
margin-left: 300px;
}
input[type=button]{
cursor: pointer;
padding: 10px 30px;
border-radius: 1px;
font-size: 2.5em;
}
input[type=text]{
padding: 10px 30px;
border-radius: 1px;
text-align: center;
font-size: 2.5em;
}
</style>
<body>
<section id="application">
<input id="substraction" type="button" value="-" onclick='substraction();'/>
<input id="number" value="1000" type="text">
<input id="addition" type="button" value="+" onclick='addition();'/>
<input type="button" value="Clear" onclick='clearText();'/>
</section>
<script>
function substraction(){
document.getElementById("tall").value -= 1000;
}
function addition(){
var numb = document.getElementById("number").value;
var add = 1000;
var total = number + add;
document.getElementById("tall").value = total;
}
function clearText(){
document.getElementById("number").value = "1000";
}
</script>
</body>
Just use a number <input> instead:
function clearText(){
document.getElementById("myNumber").value = 1000;
}
<input id="myNumber" type="number" step="1000" min="1000" max="1000000" value="1000">
<input type="button" value="Clear" onclick='clearText();'/>
This way, you can just use the step, min, and max attributes to specify the behavior of the input.
In Javascript + is also a string concatenation operator. If at least one of the operands is a String then the result is going to be a String also. You need to cast to Number type explicitly, because input value is always of a String type, even if it looks like a number "1000":
function addition() {
var number = Number(document.getElementById("number").value);
var add = 1000;
var total = number + add;
document.getElementById("tall").value = total;
}
Also instead of var numb you probably want var number.
In addition to the other answer, you're doing document.getElementById("tall").value = total; but no element with id "tall" exists. Perhaps it should be "number"?
In order to implement the minimum use the following code in subtract:
var number = Number(document.getElementById("number").value);
if(number - 1000 >= 1000)
document.getElementById("tall").value -= 1000;

How to Display Commas After Every Third Number Without Compromising Calculator

I am trying to create a loan calculator that uses commas to separate every third number. For example, $1,000,000.75.
Is there a way to display all of the input values like this, without compromising the actual calculation of numbers?
Right now, if a comma is entered in any of the inputs, than the calculated input (input that displays the calculation), throws an error (NaN). I am wondering if there is any way to do this using something such as PHP or JavaScript?
Here is a picture of a working example of my loan calculator:
Here is my full page code for the loan calculator:
<!doctype html>
<html>
<head>
<style>
body {
font-family:arial,verdana,sans-serif;
}
img a {
border:none;
}
img {
border:none;
}
.bback {
text-align:center;
width:100%;
}
#image {
width:84px;
height:41px;
}
#stretchtable {
width:60%;
max-width:500px;
min-width:200px;
}
.fontwhite {
color:white;
background-color:black;
border:4px grey solid;
padding:5px;
text-align:left;
}
</style>
<meta charset="utf-8">
<title> ::: Loan Calculator</title>
</head>
<body bgcolor="#102540">
<script language="JavaScript">
<!--
function showpay() {
if ((document.calc.loan.value == null || document.calc.loan.value.length == 0) ||
(document.calc.months.value == null || document.calc.months.value.length == 0)
||
(document.calc.rate.value == null || document.calc.rate.value.length == 0))
{ document.calc.pay.value = "Incomplete data";
}
else
{
var princ = document.calc.loan.value;
princ = princ.replace(',','');
var myfloat = parseFloat(princ);
var term = document.calc.months.value;
term = term.replace(',','');
var myfloat1 = parseFloat(term);
var intr = document.calc.rate.value / 1200;
intr = intr.replace(',','');
var myfloat2 = parseFloat(intr);
document.calc.pay.value = (myfloat * myfloat2 / (1 - (Math.pow(1/(1 + myfloat2), myfloat1)))).toFixed(2)
}
// payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months))
}
// -->
</script>
<script>
function trimDP(x, dp) {
x = parseFloat(x);
if (dp === 0)
return Math.floor(x).toString();
dp = Math.pow(10, dp || 2);
return (Math.floor((x) * dp) / dp).toString();
}
window.addEventListener('load', function () {
var nodes = document.querySelectorAll('.dp2'), i;
function press(e) {
var s = String.fromCharCode(e.keyCode);
if (s === '.')
if (this.value.indexOf('.') === -1)
return; // permit typing `.`
this.value = trimDP(this.value + s);
e.preventDefault();
};
function change() {
this.value = trimDP(this.value);
}
for (i = 0; i < nodes.length; ++i) {
nodes[i].addEventListener('keypress', press);
nodes[i].addEventListener('change', change);
}
});
</script>
<div class="bback">
<h1 style="color:white;font-size:16px;">G.B.M. Trailer Service Ltd. Loan Calculator</h1>
<a href="index.html">
<img src="images/backbutton.png" alt="Back Button" id="image" title="Back"></a><br /><br />
<center>
<div class="fontwhite" style="width:60%;">
The results of this loan payment calculator are for comparison purposes only.
They will be a close approximation of actual loan
repayments if available at the terms entered, from a financial institution. This
is being
provided for you to plan your next loan application. To use, enter values
for the
Loan Amount, Number of Months for Loan, and the Interest Rate (e.g.
7.25), and
click the Calculate button. Clicking the Reset button will clear entered
values.
</div>
</center>
</div>
<p>
<center>
<form name=calc method=POST>
<div style="color:white; font-weight:bold; border:4px grey outset; padding:0px; margin:0px;" id="stretchtable">
<table width="100%" border="1" style="border:1px outset grey">
<tr><th bgcolor="black" width=50%><font color=white>Description</font></th>
<th bgcolor="black" width=50%><font color=white>Data Entry</font></th></tr>
<tr><td bgcolor="black">Loan Amount</td><td bgcolor="black" align=center><input
type=text name=loan
size=10 class="dp2" onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black">Loan Length in Months</td><td bgcolor="black"
align=center><input type=text
name=months size=10 onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black">Interest Rate</td><td bgcolor="black" align=center><input
type=text name=rate
size=10 onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black">Monthly Payment</td><td bgcolor="black"
align=center><em>Calculated</em> <input
type=text name=pay size=10 class="dp2" onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black"align=center><input type=button onClick='showpay()'
value=Calculate></td><td bgcolor="black" align=center><input type=reset
value=Reset></td></tr>
</table>
</div>
</form>
<div style="width:60%;">
<font size=2 color=white>Enter only numeric values (no commas), using decimal points
where needed.<br>
Non-numeric values will cause errors.</font>
</center>
</div>
<p align="center"><font face="arial" size="-2">This free script provided by</font><br>
<font face="arial, helvetica" size="-2"><a href="http://javascriptkit.com">JavaScript
Kit</a></font></p>
</body>
</html>
I am looking for a solution to my problem, as I am not experienced with this type of code. Suggestions may only get me so far.
Thank you for any help. All help is greatly appreciated.
Replace this:
var intr = document.calc.rate.value / 1200;
with this
var intr = (parseFloat(document.calc.rate.value) / 1200).toString()
For the adding commas bit, replace this:
document.calc.pay.value = (princ * intr / (1 - (Math.pow(1/(1 + intr), term)))).toFixed(2)
with this
document.calc.pay.value = (princ * intr / (1 - (Math.pow(1/(1 + intr), term)))).toFixed(2).toLocaleString()
there are other ways to do it, but this seems like the fastest way without introducing more functions. JavaScript gives us toLocaleString which should be your most flexible option.
Before calculation simply use .replace(',','') to remove the commas. Then you need to cast it to to a float by using parseFloat(). Then when you go to display the numbers you can reformat it with commas if you would like.
var mystring = '10,000.12';
mystring = mystring.replace(',','');
var myfloat = parseFloat(mystring);
For adding the commas back in you can do something like this:
How to print a number with commas as thousands separators in JavaScript
From that answer:
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}

Categories