How can I make "span id" work with JavaScript? - javascript

How can I make variable <span id="price"></span> work with JavaScript?
Have to embed many VARS inside of a long HTML page and need to embed variables in long page.
Can't figure this out.
getPrice = function() {
var price = Number(document.getElementById("price").value);
var pout = Number(document.getElementById("pout").value) / 100;
var sellingprice = price;
var coop = price * pout;
var fsbo = price * pout;
var hret = price * .02;
var others = price * .06;
var saves = others - hret;
document.getElementById("sellingprice").value = sellingprice.toFixed(2);
document.getElementById("hret").value = hret.toFixed(2);
document.getElementById("fsbo").value = fsbo.toFixed(2);
document.getElementById("others").value = others.toFixed(2);
document.getElementById("saves").value = saves.toFixed(2);
}
<!DOCTYPE html>
<html>
<body>
<input id="price"> :Price
<br><br>
<input id="pout">%
<br><br>
<button onclick="getPrice()"> Calculate </button>
<br><br>
<span id="price"></span>
TEST: Price: $<input readonly id="sellingprice"><br>
FSBO $<input readonly id="fsbo"><br>
HRET $<input readonly id="hret"><br>
OTHERS $<input readonly id="others"><br>
SAVE $<input readonly id="saves"><br>
</body>
</html>

You have two elements with the same id
<span id="price"></span>
and
<input id="price"> :Price
Just because of this whenever you hit calculate it tries to get value from the span which is not available and thus returned as undefined and hence all you values may turn out to be NaN.
Also value attribute is available only to elements that are used for inputs. span does not have a value attribute for that you might have to look at innerText or innerHTML.
You must have unique id for each element . Below is a working sample of your code with span with a different id.
<!Doctype html>
<html>
<body>
<input id="price"> :Price
<br><br>
<input id="pout">%
<br><br>
<button onclick="getPrice()"> Calculate </button>
<br><br>
<span id="spanprice"></span> TEST: Price: $<input readonly id="sellingprice"><br> FSBO $<input readonly id="fsbo"><br> HRET $<input readonly id="hret"><br> OTHERS $<input readonly id="others"><br> SAVE $<input readonly id="saves"><br>
<script>
getPrice = function() {
var price = Number(document.getElementById("price").value);
var pout = Number(document.getElementById("pout").value) / 100;
var sellingprice = price;
var coop = price * pout;
var fsbo = price * pout;
var hret = price * .02;
var others = price * .06;
var saves = others - hret;
document.getElementById("sellingprice").value = sellingprice.toFixed(2);
document.getElementById("hret").value = hret.toFixed(2);
document.getElementById("fsbo").value = fsbo.toFixed(2);
document.getElementById("others").value = others.toFixed(2);
document.getElementById("saves").value = saves.toFixed(2);
}
</script>
</body>
</html>
Hope this helps :)

Related

Simple JavaScript function returns function and not value

I'm just starting out and I'm trying to build a simple calculation function that will display the result of 2 numbers on a page. When the submit button is hit the output is the function and not the value. Where have I gone wrong?
HTML
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="test">Test</div>
JS
<script>
'use strict';
var total = function() {
var price = function() {
parseFloat(document.getElementById("price"));
}
var tax = function() {
parseFloat(document.getElementById("tax"));
}
var final = function() {
final = price * tax;
final = total
}
document.getElementById("output").innerHTML = final;
};
</script>
You have several issues with your javascript. Let's break them down one by one:
var price = function() {
parseFloat(document.getElementById("price"));
}
document.getElementById returns an element. parseFloat would try to calculate the element, and not the value in this case (Which would always be NaN or Not a Number). You want the value of this element, so using .value will return the value. Furthermore, you're not actually doing anything with the value. (You should use return to return the float found, or set it to another variable.)
var final = function() {
final = price * tax;
final = total
}
price and tax are both functions in this case. You can't simply multiply them to get your desired result. Using var total = price() * tax(); will set the variable total to the float returned from price() and tax() now. Returning this value to the function will fix the next line:
document.getElementById("output").innerHTML = final;
final here is also a function. You want to call it by using final().
Your final script:
var total = function() {
var price = function() {
return parseFloat(document.getElementById("price").value);
}
var tax = function() {
return parseFloat(document.getElementById("tax").value);
}
var final = function() {
var total = price() * tax();
return total
}
document.getElementById("output").innerHTML = final();
};
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="output">test</div>
You have several issues, you put some code into function without calling them.
Another problem is, you need the value of the input tags.
'use strict';
var total = function() {
var price = parseFloat(document.getElementById("price").value);
// get value ^^^^^^
var tax = parseFloat(document.getElementById("tax").value)
// get value ^^^^^^
// calculate directly the final value
var final = price * tax;
document.getElementById("output").innerHTML = final;
};
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
<div id="output"></div>
Delete
var final = function() {
final = price * tax;
final = total
}
and instead put
return price * tax;

javascript calculator works only after refreshing the page

I made this calculator http://fernandor80.neocities.org/plancalc/tomx2.html
and it always returns Nan, but once you reload it (with the previously entered inputs), it works...
I've been looking around but I can not figure it out... So I'm here because I really want to get it to work.
here is the code to it:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Plant Calc V1.2</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<main>
<form name="plantrow" method=POST>
<h1>How many trays per round?</h1>
<input type="text" id="ppr">
<br>
<h1>How many rows (6,10,12)?</h1>
<input type="text" id="bed">
<input type="button" id="firstcalc" value="go!" onClick="row()">
</form>
<br>
<h2>Trays per row::</h2>
<h1 id="ppb"></h1>
<form name="field" method=POST>
<h1>Total rows in the field??</h1>
<input type="text" id="totalb">
<input type="button" id="secondcalc" value="go!" onClick="total()">
</form>
<h1>You need:::</h1>
<h1 id="totalp"></h1>
<h1>trays</h1>
<div id="bins">
45 count bins<h2 id="bin45"></h2>
90 count bins<h2 id="bin90"></h2>
</div>
<form name="nowplants" method=POST>
<h1> How much plant you have now(trays)???</h1>
<input type="text" id="nowp">
<input type="button" id="thirdcalc" value="go" onClick="now()">
</form>
<h1>You can plant ::</h1>
<h1 id="nowb"></h1>
<h1>rows</h1>
</main>
<script language="JavaScript">
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr/bed ;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp/45 ;
var bin90 = totalp/90 ;
var nowp = document.getElementById("nowp").value;
var nowb = nowp/ppb ;
function row(){
document.getElementById("ppb").innerHTML = ppb;
}
function total(){
document.getElementById("totalp").innerHTML = totalp;
document.getElementById("bin45").innerHTML = bin45;
document.getElementById("bin90").innerHTML = bin90;
}
function now(){
document.getElementById("nowb").innerHTML = nowb;
}
</script>
</body>
</html>
Also it doesnt work on mobile devices..I made a pure javascript prompt based calculator for that, but for the purpose of learning i would like some pointers.
I really feel bad about asking a question thats been answered hundreds of times. Sorry, I just had to..
the values of ppr, bed, and ppb are calculated when the page first loads. Thus it's a NaN.
You should consider move at least the data retrieval and calculation inside function row().
One simple way to debug issue like this, if you don't use any IDE, it to press f12 in your browser and open dev mode where you can set break point and check the current value of your variables.
You have dependency over other variable in every function. Instead of using global variables, you can access value in each function.
function row() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
document.getElementById("ppb").innerHTML = ppb;
}
function total() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp / 45;
var bin90 = totalp / 90;
document.getElementById("totalp").innerHTML = totalp;
document.getElementById("bin45").innerHTML = bin45;
document.getElementById("bin90").innerHTML = bin90;
}
function now() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp / 45;
var bin90 = totalp / 90;
var nowp = document.getElementById("nowp").value;
var nowb = nowp / ppb;
document.getElementById("nowb").innerHTML = nowb;
}
<main>
<form name="plantrow" method=POST>
<h1>How many trays per round?</h1>
<input type="text" id="ppr">
<br>
<h1>How many rows (6,10,12)?</h1>
<input type="text" id="bed">
<input type="button" id="firstcalc" value="go!" onClick="row()">
</form>
<br>
<h2>Trays per row::</h2>
<h1 id="ppb"></h1>
<form name="field" method=POST>
<h1>Total rows in the field??</h1>
<input type="text" id="totalb">
<input type="button" id="secondcalc" value="go!" onClick="total()">
</form>
<h1>You need:::</h1>
<h1 id="totalp"></h1>
<h1>trays</h1>
<div id="bins">
45 count bins
<h2 id="bin45"></h2>
90 count bins
<h2 id="bin90"></h2>
</div>
<form name="nowplants" method=POST>
<h1> How much plant you have now(trays)???</h1>
<input type="text" id="nowp">
<input type="button" id="thirdcalc" value="go" onClick="now()">
</form>
<h1>You can plant ::</h1>
<h1 id="nowb"></h1>
<h1>rows</h1>
</main>
It will always NaN because your call values of ppr, bed, and ppb when just first page loaded ! At that page loaded time ,you didn't have any value so NaN getting.So when you click ,you should call that value again ,make it function to call values will be more better...
here I push init() to get value onclick
<script type="text/javascript">
var ppr,bed,ppb,totalp,totalb,bin45,bin90,nowb,nowb;
function init(){
ppr = parseFloat(document.getElementById("ppr").value);
bed = parseFloat(document.getElementById("bed").value);
ppb = ppr/bed ;
totalb = parseFloat(document.getElementById("totalb").value);
totalp = totalb * ppb;
bin45 = totalp/45 ;
bin90 = totalp/90 ;
nowp = document.getElementById("nowp").value;
nowb = nowp/ppb ;
}
function row(){
init();
document.getElementById("ppb").innerHTML = ppb;
}
</script>

Passing Info From form to form Javascript

I have a very basic form that I want to pass data from another form on it without using php at all. Both forms appear properly but I cannot figure out how to transfer data from the first form to the second one with javascript code.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<form action"" method="get" onsubmit="submitForm();" name="submitForm">
Company Name:<input type="text"name="companyName"><br><br>
Owner: <input type="text" name="compOwner"><br><br>
Address: <input type="text" name="address"><br><br>
Phone Number:<input type="text" name="phoneNum"><br><br>
Annual Sales($)<input type="text" name="annualSales"><br><br>
Borrow Amount($)<input type="text" name="borrowAmount"><br><br>
Payment Terms(Months)<input type="text" name="paymentTerms"><br><br>
<input type="submit" value="Submit" onclick="submitForm();">
</form>
<form action"" method="get" name="secondForm">
Name of Borrowing Company<input type="text"id="compName"><br><br>
Annual Sales<input type="text"id="annSales"><br><br>
Borrow Amount<input type="text"id="amountBorrowed"><br><br>
Payment Terms<input type="text"id="payTerms"><br><br>
Total Interest On Loan<input type="text"id="totalInterest"><br><br>
Total Payment<input type="text"id="totalPay"><br><br>
Total Profit <input type="text"enabled="false" id="totalProfit"><br><br>
</form>
<script>
function submitForm()
{
compName = document.forms["submitForm"]["companyName"].value;
annualSales = document.forms["submitForm"]["annualSales"].value;
borrowAmount = document.forms["submitForm"]["borrowAmount"].value;
months = document.forms["submitForm"]["paymentTerms"].value;
totalInterest = borrowAmount * (months/12) * 0.03;
totalPayment = borrowAmount + totalInterest;
profit = totalPayment - borrowAmount;
document.getElementById('compName').setAttribute(value, compName);
document.getElementById('annSales').value = annualSales;
document.getElementById('amountBorrowed').value = borrowAmount;
document.getElementById('payTerms').value = months;
document.getElementById('totalInterest').value = totalInterest;
document.getElementById('totalPay').value = totalPayment;
document.getElementById('totalProfit').value = profit;
}
</script>
</body>
</html>
I figured it out. There are several problems with this code actually.
First, name of the first form element clashes with name of your function. That is because when an element has a name attribute, it creates a new variable in JS global scope and rewrites your function, because it has the same name. Your form name attribute must be something else that your function name.
<form action"" method="get" onsubmit="submitForm();" name="submitF">
Next, input type="submit" refreshes the page, which you probably don't want. You could add a button element after the form.
</form>
<button onclick="submitForm()">Submit</button>
In JS, submitF is a variable with your form element (thanks to the name attribute), so you can write it simpler without use of document.forms.
function submitForm() {
compName = submitF["companyName"].value;
annualSales = submitF["annualSales"].value;
borrowAmount = submitF["borrowAmount"].value;
months = submitF["paymentTerms"].value;
(...)
}
Also, setAttribute(value, compName) doesn't work. It just doesn't. Assign to value instead like in the rest of the code.
My whole working code looks like this:
<html>
<head>
<title>HTML Form</title>
<script type="text/javascript">
function submitForm() {
compName = submitF["companyName"].value;
annualSales = submitF["annualSales"].value;
borrowAmount = submitF["borrowAmount"].value;
months = submitF["paymentTerms"].value;
totalInterest = borrowAmount * (months/12) * 0.03;
totalPayment = borrowAmount + totalInterest;
profit = totalPayment - borrowAmount;
document.getElementById('compName').value = compName;
document.getElementById('annSales').value = annualSales;
document.getElementById('amountBorrowed').value = borrowAmount;
document.getElementById('payTerms').value = months;
document.getElementById('totalInterest').value = totalInterest;
document.getElementById('totalPay').value = totalPayment;
document.getElementById('totalProfit').value = profit;
}
</script>
</head>
<body>
<form action"" method="get" onsubmit="submitForm();" name="submitF">
Company Name:<input type="text"name="companyName"><br><br>
Owner: <input type="text" name="compOwner"><br><br>
Address: <input type="text" name="address"><br><br>
Phone Number:<input type="text" name="phoneNum"><br><br>
Annual Sales($)<input type="text" name="annualSales"><br><br>
Borrow Amount($)<input type="text" name="borrowAmount"><br><br>
Payment Terms(Months)<input type="text" name="paymentTerms"><br><br>
</form>
<button onclick="submitForm()">Submit</button>
<form action"" method="get" name="secondForm">
Name of Borrowing Company<input type="text"id="compName"><br><br>
Annual Sales<input type="text"id="annSales"><br><br>
Borrow Amount<input type="text"id="amountBorrowed"><br><br>
Payment Terms<input type="text"id="payTerms"><br><br>
Total Interest On Loan<input type="text"id="totalInterest"><br><br>
Total Payment<input type="text"id="totalPay"><br><br>
Total Profit <input type="text"enabled="false" id="totalProfit"><br><br>
</form>
</body>
</html>
That's it. Hope I helped.
EDIT: Also, you should always put your JS code in your <head>, unless you have a very good reason not to.
You might want to change document.getElementById('compName').setAttribute(value, compName);
to
document.getElementById('compName').value = compName;
Also, you should convert your number values from String to an Integer
ex.
annualSales = parseInt(document.forms["submitForm"]["annualSales"].value)
Other than that, the javascript seems fine.
UPDATE:
Upon investigating further. Your submit is occurring before the javascript is run, that is why the fields are not getting populated. I would suggest you put your javascript in an event listener for submit.
document.forms['submitForm'].submit(function() {
compName = document.forms["submitForm"]["companyName"].value;
annualSales = document.forms["submitForm"]["annualSales"].value;
borrowAmount = document.forms["submitForm"]["borrowAmount"].value;
months = document.forms["submitForm"]["paymentTerms"].value;
totalInterest = borrowAmount * (months/12) * 0.03;
totalPayment = borrowAmount + totalInterest;
profit = totalPayment - borrowAmount;
document.getElementById('compName').setAttribute(value, compName);
document.getElementById('annSales').value = annualSales;
document.getElementById('amountBorrowed').value = borrowAmount;
document.getElementById('payTerms').value = months;
document.getElementById('totalInterest').value = totalInterest;
document.getElementById('totalPay').value = totalPayment;
document.getElementById('totalProfit').value = profit;
});
NOTE: Your page will refresh when you do a submit, and you won't see the values be populated.

math function with jQuery

Trying to using jQuery do some basic math functions.
Step 1. User enter Gross weight, and Tare weight, my function auto generate Net weight, which is Gross weight minus Tare weight.(This step works)
Step 2. User enter Price per pound, my function use Price per pound times Net weight to calculate total cost.
So far my code looks like this, it returns the net weight but does not return the total cost:
<script>
$(document).ready(function() {
$(".sub").focusout(function() {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = gross-tare;
$("#net").html(Math.round(net*1000)/1000);
});
});
$(document).ready(function() {
$(".sub1").focusout(function() {
$("#total").html('');
var net = $("#net").val();
var ppp = $("#ppp").val();
var total = net*ppp;
$("#total").html(Math.round(total*1000)/1000);
});
});
</script>
And the HTML:
<input type='number' name='gross' id=gross class=sub>
<input type='number' name='tare' id=tare class=sub>
<p id=net name='net'></p>
<input type="number" id=ppp name="ppp" class=sub1/>
<p id=total name='total'></p>
Forgive me if I am making stupid mistakes as I barely know jQuery, this is just one requirement for my project that I am working on.
A few minor things:
-id=gross should have quotes id='gross'
-$("#net").val(); net doesn't have a value, its a p, so use text()
-you'll want to use parseInt or parseFloat
Example:
$(document).ready(function () {
$(".sub").focusout(function () {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = gross - tare;
$("#net").html(Math.round(net * 1000) / 1000);
});
$(".sub1").focusout(function () {
$("#total").html('');
var net = parseInt($("#net").text());
var ppp = parseInt($("#ppp").val());
var total = net * ppp;
$("#total").html(Math.round(total * 1000) / 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type='number' name='gross' id='gross' class='sub'/>
<input type='number' name='tare' id='tare' class='sub'/>
<p id='net' name='net' class='sub1'></p>
<input type="text" id='ppp' name="ppp" class='sub1'/>
<p id='total' name='total'></p>
Put the class names/ ids or other attributes in quotes. They are parsed wrongly by the browser. Check using "firebug" or "inspect element".
Problem in your code: You are using '$("#net").val()', but $.val() works only on input fields but #net is a <p> tag, so get its text using $.html().
Your code should be like this
HTML:
<input type='number' name='gross' id=gross class="sub">
<input type='number' name='tare' id=tare class="sub">
<p id="net" name='net'></p>
<input type="number" id="ppp" name="ppp" class="sub1"/>
<p id="total" name='total'></p>
SCRIPT:
$(document).ready(function() {
$(".sub").focusout(function() {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = gross-tare;
$("#net").html(Math.round(net*1000)/1000);
});
});
$(document).ready(function() {
$(".sub1").focusout(function() {
$("#total").html('');
var net = parseFloat($("#net").html());
var ppp = parseFloat($("#ppp").val());
var total = net*ppp;
$("#total").html(parseFloat(total));
});
});

JavaScript function Not Working with onchange attribute of input tag

I have been trying to replicate Duncan Donut Example from HEAD FIRST JAVASCRIPT, but the function subTotal() is never triggered by onchange event and when I look into HTML REFERENCE, I did not find any onchange event in list provided.
Duncan.html
<html>
<head><title>Duncan Online Donut's Service</title></head>
<script type="text/javascript">
function subTotal(){
document.write("working");
const TAXRATE = 0.095;
const DONUTRATE = 0.5;
var tax = 0;
var subTotal = 0;
var total = 0;
var cakedonut = parseInt(document.getElementById("cakedonut").value);
var glazedonut = parseInt(document.getElementById("glazedonut").value);
if(isNaN(cakedonut))
cakedonut = 0;
if(isNaN(glazedonut))
glazedounut = 0;
subTotal = (cakedonut + glazedonut)* DONUTRATE ;
tax = subTotal * TAXRATE ;
total = subTotal + tax ;
document.getElementById("subTotal").value = "$" + subTotal.toFixed(2);
document.getElementById("tax").value = "$" + tax.toFixed(2);
document.getElementById("total").value = "$" + total.toFixed(2);
}
</script>
<body>
<h1><b><i>Duncan Online Donut's Service</i></b></h1>
<form>
Name : <input id="name" type="text" name="name"/><br><br>
#no of cake donuts : <input id="cakedonut" type="text" name="cakedonut" onchange="subTotal()"/><br><br>
#no of glazed donuts : <input id="glazedonut" type="text" name="glazedonut" onchange="subTotal("/><br><br>
subTotal : <input id="subTotal" type="text" name="subTotal" /><br><br>
tax : <input id="tax" type="text" name="tax" /><br><br>
Total : <input id="total" type="text" name="total"/><br><br>
<input type="submit"/><br><br>
</form>
</body>
</html>
JSFiddle
The above is my code. I tried running this on IE and Chrome but in vain. Thanks in advance.
The problem is you have defined a variable and a function both with the same name subTotal and the variable declaration is overriding the function definition. Change the function name to anything say subTotal1 it will work.
JSBIN link
change your function name. don't use subTotal(); and don't use document.write("working");
function subTotalnew()
{
alert('working');
}
onchange="subTotalnew() it gonna be work after input blur.
oninput="subTotalnew() it gonna be work when input entering something.

Categories

Resources