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(".");
}
Related
I am new to Javascript and just getting into it for my web design class. I am working on a project with Javascript inside HTML. I have it all written, but the HTML doesn't seem to call the Javascript function. I've been searching for a solution but can't seem to get anything to work. The code is:
<html>
<head>
<script>
var calculateInterest = function(){
var rate;
var total;
var years = document.getElementById("years").value;
var principleAmount = document.getElementById("principal").value;
var interestRate = document.getElementById("intrest").value;
if ((interestRate >= 0) && (interestRate <= 15)) {
rate = interestRate / 100;
if ((principleAmount >= 0) && (principleAmount <= 10000)) {
total = principleAmount * (1 + rate * years);
document.getElementById("total_with_intrest").value = total;
}
else {
message-box ("Invalid data for principle amount.");
}
}
else {
message-box ("Invalid data for interest rate.");
}
}
</script>
<style>
form{ border: solid blue;
width:40em;
padding:0.5em;}
input{padding: 0.5em;}
</style>
</head>
<body>
<form>
Enter Principal Ammount : <input type="text" id ="principal" />
</br>
Enter Intrest Rate : <input type="text" id ="intrest" />
</br>
Enter Number of Years : <input type="text" id ="years" />
</br>
Grand Ammount : <input type="text" id ="total_with_intrest" disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick=calculateInterest()/> </br>
</form>
</body>
</html>
The browser error is "SyntaxError: expected expression, got '}' " on line 2 but I just can't see what the issue is. Any help is greatly appreciated!
Side note, I am aware there are some weird spelling mistakes. My instructor is from India and not totally fluent in English. She made the HTML file for us to use and we just have to put in the Javascript.
There is no message-box function. Did you mean alert()? Your code currently works, with those changes:
var calculateInterest = function(){
var rate;
var total;
var years = document.getElementById("years").value;
var principleAmount = document.getElementById("principal").value;
var interestRate = document.getElementById("intrest").value;
if ((interestRate >= 0) && (interestRate <= 15)) {
rate = interestRate / 100;
if ((principleAmount >= 0) && (principleAmount <= 10000)) {
total = principleAmount * (1 + rate * years);
document.getElementById("total_with_intrest").value = total;
}
else {
alert("Invalid data for principle amount.");
}
}
else {
alert("Invalid data for interest rate.");
}
}
form{ border: solid blue;
width:40em;
padding:0.5em;}
input{padding: 0.5em;}
<form>
Enter Principal Amount : <input type="text" id ="principal" />
</br>
Enter Interest Rate : <input type="text" id ="intrest" />
</br>
Enter Number of Years : <input type="text" id ="years" />
</br>
Grand Amount : <input type="text" id ="total_with_intrest" disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick="calculateInterest()" /> </br>
</form>
Small Nitpick: Fixed some small typos not related to code. Ammount => Amount. Intrest => Interest.
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
JS:
function myarray (){
}
var starting=document.getElementById("starting");
var ending=document.getElementById("ending");
var step=document.getElementById("step");
var results=document.getElementById("myarray")
if (i>=0){
var result=starting
}
for (var starting>=0; myarray<=ending; i+=step)
document.writeln(myarray[i+=step]){
}
HTML:
<div id="results">Here are the even numbers between "startingnumber" and "endingnumber" by "step"&nnsp's
<!DOCTYPE html>
<html>
<head>
<title>A Web Page</title>
</head>
<script src="Guild_Practice.js"></script>
<style media="screen">
table {
width:40%;
}
.titles {
text-align: right;
color: green;
font-family: arial;
font-weight: bold;
padding-bottom: 10px;
}
caption {
font-size: 32px;
font-weight: bold;
font-family: cursive;
color: red;
}
.displayevens {
text-align: center;
padding-top: 10px;
}
}
</style>
<body>
<table>
<caption>Sample</caption>
<form>
<tr>
<!--Starting Number Line with Form -->
<td class="titles">Starting Number</td>
<td class="align-left"><input type="text" id="starting"></td>
</tr>
<tr>
<!-- Ending Number Line with Form -->
<td class="titles">Ending Number</td>
<td class="align-left"><input type="text" id="ending"></td>
</tr>
<tr>
<!-- Step Line with Form -->
<td class="titles">Step</td>
<td class="align-left"><input type="text" id="step"></td>
</tr>
<tr>
<!-- Button covered in both columns -->
<td class="displayevens" colspan="2"><button type="button">Display Evens</button></td>
</tr>
</form>
</table>
</body>
</html>
I have to allow a user to enter a starting number an ending number and a step value into three textboxes on a page (which I have created). A button will be present that when clicked should output all the even numbers between the start and end value.
My questions are:
How does my js code look so far?
How do I make a phrase such as: "Here are the even numbers between 4 and 20 by 3's" and then list out the numbers. It will appear once I click the button.
You could take the values and cast it to number with an unary plus and iterate from starting to ending with the given step. With each loop check if the actual counter is even and add it to the result set.
Later display the result in results.
function myarray() {
var starting = +document.getElementById("starting").value,
ending = +document.getElementById("ending").value,
step = +document.getElementById("step").value,
results = document.getElementById("results"),
i,
array = [];
for (i = starting; i <= ending; i += step) {
i % 2 || array.push(i);
}
results.innerHTML = array.join(', ');
}
<pre><form>Starting Number: <input type="text" id="starting"><br>Ending Number: <input type="text" id="ending"><br>Step: <input type="text" id="step"><br><button type="button" onclick="myarray()">Display Evens</button></form><div id="results"></div></pre>
So it isn't so much that you want the even numbers, you simply want the incremental steps between your starting and ending point. Is that correct? And I assume this is a school assignment? Try something like this to kick you off. I've created the HTML elements, and I've retrieved the values of the inputs. Now you get to create the logic for the increment (try a FOR loop) and insert the results into the progression-pane.
/*****
* When the "show me!" button gets clicked,
* there's a few things we do: get the values of
* the inputs, loop from the starting value to
* the ending value by a given increment (default
* increment of two), and output the result to a div.
*****/
runCounter = function() {
// This is the location we'll put the result
var contentPane = document.getElementById("progression-pane");
// This will be the output string
var contentString = "";
// retrieve the values given AND MAKE THEM
// INTEGERS! We could do floats, but it's
// darn important to make them numbers.
var startingValue = parseInt(document.getElementById("startingValue").value);
var endingValue = parseInt(document.getElementById("endingValue").value);
var increment = parseInt(document.getElementById("incrValue").value);
if (startingValue && endingValue) {
// So long as we actually HAVE a staring and ending value...
if (!increment) increment = 2;
// If we don't have an increment given, let's count by twos!
contentString += "<p>The values between " + startingValue + " and " + endingValue + " in increments of " + increment + ":</p><ul>";
for (i = startingValue; i <= endingValue; i += increment) {
// If we are here, we have all three: start, end and increment
contentString += "<li>" + i + "</li>";
}
contentString += "</ul>";
// We've finished formatting the string,
// let's output it to the proper div.
// Note that I'm using innerHTML,
// document.writeln is considered bad.
contentPane.innerHTML = contentString;
}
}
label {
display: block;
font-weight: bold;
}
<label for="startingValue">Start:</label>
<input type="text" id="startingValue" />
<label for="endingValue">End:</label>
<input type="text" id="endingValue" />
<label for="startingValue">Increment:</label>
<input type="text" id="incrValue" />
<button onclick="runCounter()">Show me!</button>
<div class="content-pane">
<h2>Your progression:</h2>
<div id="progression-pane">
</div>
</div>
The bulk of the above javascript is actually comments discussing what I'm doing. Get in that habit, so you don't lose track of variables! And yours works fine, but innerHTML is considered better form than document.writeln
Ok, so if in fact you want the EVEN numbers at the given step intervals, change the line that actually appends the line items like this:
// Now, we want to see if this is an even number
if(i%2 == 0)
contentString += "<li>" + i + "</li>";
See this version running as a fiddle here
I'm very new to Javascript and this website, but I'm looking for help on a project of mine.
It's a little rough so far and not complete, but I can't move on until I figure out how to actually get the computations to show up. If I could get help figuring out why the first apple total isn't computing, that would be great!
Here's my full (work in progress) html page:
<html>
<head>
<title>Order Form</title>
<style>
.inBox { width:60px; text-align:right; border: 1px solid green; }
.thWide { width:80px; text-align:right; }
</style>
<script type="text/javascript">
function compute()
{
// Pointers to red asterisks
var spnA = document.getElementById("spnA");
var spnP = document.getElementById("spnP");
var spnG = document.getElementById("spnG");
// Assume no errors yet
var message = "";
spnL.style.display = "none";
spnW.style.display = "none";
spnH.style.display = "none";
var apple = form1.txtA.value;
if (apple == "")
apple = 1;
else
apple = parseFloat(apple);
if ( isNaN(apple) )
{
spnA.style.display = "inline";
message = message + "Apple is bad\n";
form1.txtA.select();
}
var pear = form1.txtP.value;
if (pear == "")
pear = 1;
else
pear = parseFloat(pear);
if ( isNaN(pear) )
{
spnP.style.display = "inline";
message = message + "Pear is bad\n";
form1.txtP.select();
}
var grape = form1.txtG.value;
if (grape == "")
grape = 1;
else
grape = parseFloat(grape);
if ( isNaN(grape) )
{
spnG.style.display = "inline";
message = message + "Grape is bad\n";
form1.txtG.select();
}
if ( message != "" )
{
// Show error and clear subA
alert(message);
form1.txtsubA.value = "";
}
else
{
// Compute subA
var subA = length * 5.49;
form1.txtsubA.value = subA;
form1.txtA.select();
}
}
</script>
</head>
<body>
<form id="form1">
<table border="2">
<tr><th colspan="4">Volume Box</th></tr>
<tr><th>Quantity</th><th>Item</th><th>Unit Prics</th><th>Totals</th></tr>
<tr>
<th class="thWide">
<span id="spnA" style="color:red; font-weight:bold; display:none;">*</span>
<input type="text" id="txtA" class="inBox" tabindex="1" autofocus />
</th><td>Apples</td><td>$5.49</td>
<th style="width:80px;"><input type="text" id="txtsubA" class="inBox" readonly /></th>
</tr><tr>
<th class="thWide">
<span id="spnP" style="color:red; font-weight:bold; display:none;">*</span>
<input type="text" id="txtP" class="inBox" tabindex="1" autofocus />
</th><td>Pears</td><td>$6.49</td>
<th style="width:80px;"><input type="text" id="txtsubP" class="inBox" readonly /></th>
</tr><tr>
<th class="thWide">
<span id="spnG" style="color:red; font-weight:bold; display:none;">*</span>
<input type="text" id="txtG" class="inBox" tabindex="1" autofocus />
</th><td>Grapes</td><td>$7.49</td>
<th style="width:80px;"><input type="text" id="txtsubG" class="inBox" readonly /></th>
</tr>
<tr><th colspan="4">
<input type="button" value="Compute" onclick="compute();" tabindex="4" />
</th></tr>
</table>
</form>
</body>
</html>
The console in your browser can be very helpful in diagnosing any problems. For example, your code gives this error in the console:
test.html:18 Uncaught ReferenceError: spnL is not defined
I assume you meant for this part:
spnL.style.display = "none";
spnW.style.display = "none";
spnH.style.display = "none";
to be:
spnA.style.display = "none";
spnP.style.display = "none";
spnG.style.display = "none";
As for your problem, the issue is in this part:
// Compute subA
var subA = length * 5.49;
Length isn't defined anywhere, you probably mean:
// Compute subA
var subA = apple * 5.49;
And then you will also probably want to change the line after that from
form1.txtsubA.value = subA;
to
form1.txtsubA.value = subA.toFixed(2);
which will only show 2 decimal places.
Get rid of (or comment out):
spnL.style.display = "none";
spnW.style.display = "none";
spnH.style.display = "none";
Collect the values provided in the form (add ".value"):
// Pointers to red asterisks
var spnA = document.getElementById("txtA").value;
var spnP = document.getElementById("txtP").value;
var spnG = document.getElementById("txtG").value;
Swap length for declared values:
// Compute subA
var subA = spnA * 5.49;
And enjoy!
Ive stared to learn Javascript, im trying to create a calculator, which just multiplies 2 numbers, i get this error in my browser console.
Can anybody help?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calc</title>
<style>#result{position: relative; top: 5px;}</style>
</head>
<body>
<input type="number" id="first"> *
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
<script>
function res() {
var a = document.getElementById("first").value;
var b = document.getElementById("second").value;
var span = document.getElementById("span");
if(a != 0 && b !=0) {
span.innerHTML = a * b;
}
if(a = 0 || b = 0) {
span.innerHTML = "0"; // I know browser can do it automatically without 21 and 22 strings but i need that it works this way.
}
}
</script>
</body>
</html>
Firstly, if you are going to do any math with text input, you have to convert them to a number. You can use parseInt(num, 10) or parseFloat(num).
Secondly, in one of your if-statements, you are not actually comparing the variables a and b, but assigning 0 to them. Use two equal signs == to compare variables.
Thirdly, you could just check for whether they are numbers instead using isNaN(num). Doing so would eliminate the first if-statement.
function res() {
var a = parseFloat(document.getElementById("first").value);
var b = parseFloat(document.getElementById("second").value);
var span = document.getElementById("span");
if (isNaN(a) || isNaN(b)) {
span.innerHTML = "0";
}
else {
span.innerHTML = a * b;
}
}
<input type="number" id="first">*
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
check here your corrected code
<html>
<head>
<title>Calc</title>
<style>#result{position: relative; top: 5px;}</style>
</head>
<body>
<input type="number" id="first"> *
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
<script>
function res() {
var a = document.getElementById("first").value;
var b = document.getElementById("second").value;
var span = document.getElementById("span");
if(a != 0 && b !=0) {
span.innerHTML = a * b;
}
if(a == 0 || b == 0) {
span.innerHTML = "0"; // I know browser can do it automatically without 21 and 22 strings but i need that it works this way.
}
}
</script>
</body>
</html>