Passing Info From form to form Javascript - 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.

Related

Html form input to variable for use in a js function

<form onsubmit="calculos(); return false;">
<label for="gasto">
<span> Valor </span>
<input
required
type="number"
id="gasto"
class="gasto"
name="gasto"
placeholder="Valor.."
/>
</label>
<input type="submit" value="submit"/>
</form>
script trying to take that input into a variable for a function to
return that inpunt and * to print in web
<script language="javascript">
function calculos() {
document.getElementById("gasto").value;
var num1 = document.getElementById("gasto").value;
Honorarios = num1 * 0.3;
Escribania = num1 * 0.2;
sellos = num1 * 0.05;
return (Honorarios, Escribania, sellos);
console.log(gasto);
console.log(Honorarios);
console.log(Escribania);
console.log(sellos);
alert(gasto, Honorarios, Escribania, sellos);
}
calculos();
</script>
sorry if i dont explain good enough im learing html and js and wanted to make a calculator that you input a amount and the algorithm gives you back that amount * by 0.05 and others thanks
I edited your code, and removed the unnecessary lines, also moved the label HTML element which was badly placed, it works now, watch out for console log.
I also combined all results into a single string before alert line.
function calculos() {
document.getElementById("gasto").value;
var num1 = document.getElementById("gasto").value;
Honorarios = num1 * 0.3;
Escribania = num1 * 0.2;
sellos = num1 * 0.05;
console.log(Honorarios);
console.log(Escribania);
console.log(sellos);
let allOfThem = `Honorarios: ${Honorarios}
Escribania: ${Escribania}
sellos: ${sellos}`
alert(allOfThem);
}
//calculos(); This function SHOULD never be here, as it will be called everytime.
<form onsubmit="calculos(); return false;">
<label for="gasto">
<span> Valor </span>
</label> <!-- This was moved here to the right place, it was at the end of form -->
<input
required
type="number"
id="gasto"
class="gasto"
name="gasto"
placeholder="Valor.."
/>
<input type="submit" value="submit"/>
</form>

How can I make "span id" work with 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 :)

Javascript Client-Side Beverage Price Calculator

I'm working on a personal project where I'd like to take user input via a form's text boxes, perform a calculation on it, and display the result on the same page. I work in a restaurant and would like to simplify the process of calculating the cost of a cocktail. I'm new to Javascript and this is my first proper project. I'm having difficulty figuring out what to do after storing the user input into a variable. I have created an object "drinkPrices" with the three different categories of drink types under the "name" keyword, the respective prices under the other keywords, and then a method that calculates the prices. I'm unsure if this approach is correct and ANY feedback/suggestions/help would be much appreciated.
Main difficulties:
1. Am I storing the user input correctly?
2. How do I take the user input and reference it to the method in the object I have created?
3. How do I display the results of the calculation on the page?
<!DOCTYPE html>
<html lang="en">
<head>
<script src="submitAlert.js"></script>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id="theform">
Enter Spirit Name:<br>
<input type="text" id="sname" name="spiritname"><br>
Enter Spirit Amount (in ounces):<br>
<input type="text" id="samount" name="spiritamount">
<br><br>
<input type="submit" value="submit" onclick="return foo();" />
</form>
</body>
<p id="outputarea"> ...Output area is right here...</p>
</html>
Javascript:
var drinkPrices = {
name: ['rail', 'call', 'premium'],
railPrice: 4,
callPrice: 6,
premiumPrice: 8,
quantity: 0,
calculatePrice: function() {
if (name === 'rail') {
calculatePrice = quantity * railPrice;
} else if (name === 'call') {
calculatePrice = quantity * callPrice;
} else if (name ==='premium') {
calculatePrice = quantity * premiumPrice;
}
return this.calculatePrice;
}
}
//this is the code I have for when the user hits submit. I am missing a lot//
function foo() {
var a = document.getElementById("sname").value;
var b = document.getElementById("samount").value;
alert("Submit button clicked!");
return true;
}
Just use a name-price map:
const price = {
rail:2,
call:4,
premium:6
};
Then you can simply get the price:
function calculatePrice() {
const name = document.getElementById("sname").value;
const amount = document.getElementById("samount").value;
alert(`It costs ${amount * prices[name]}`);
}
Hint: Don't use a form if you dont want to send something to the server (just use <input> only), it makes things complicated, and give appropriate names to variables and functions!
Here are some improvements for your further coding:
Replace input elements with select lists when you dealing with a predefined list of options, in this way you prevent accedential typos by the user.
When you use select and you're only interessted in corresponding values, use the value attribute on option tags.
When you need numerical inputs, use <input type="number"> or <input type="range" min="0" max="100" step="1"> (min/max/step are optional and can be added to number-inputs too).
Use the onsubmit on forms instead of onclick on buttons to let the browser validate the inputs (part of better practice).
Here I've hacked together an example:
document.querySelector('#theform').addEventListener('submit', function(e) {
e.preventDefault();
let price = this.spirit.value * 1;
let amount = this.spiritamount.value * 1;
let total = (price * amount).toFixed(2);
document.querySelector('#outputarea').textContent = total;
});
<form id="theform">
Enter Spirit Name:<br>
<select name="spirit">
<option value="4">rail</option>
<option value="6">call</option>
<option value="8">premium</option>
</select><br>
Enter Spirit Amount (in ounces):<br>
<input type="number" name="spiritamount" value="1">
<br><br>
<button>Calculate</button>
</form>
<p id="outputarea">0.00</p>
Here is another example with listed entries:
let receipt = {};
const prices = {
'rail': 4,
'call': 6,
'premium': 8
};
// clear the receipt
document.querySelector('#reset').addEventListener('click', function(e) {
e.preventDefault();
receipt = {};
document.querySelector('#outputarea').innerHTML = '';
});
document.querySelector('#theform').addEventListener('submit', function(e) {
e.preventDefault();
let spirit = this.spirit.value;
let amount = this.spiritamount.value * 1;
if(spirit in receipt) {
receipt[spirit] += amount;
} else {
receipt[spirit] = amount;
}
let list = '';
let total = 0;
for(const e in receipt) {
let sum = prices[e] * receipt[e];
list += `<div>${e} x ${receipt[e]} = ${sum.toFixed(2)}</div>`;
total += sum;
}
list += `<hr>${total.toFixed(2)} ยค`;
document.querySelector('#outputarea').innerHTML = list;
})
<form id="theform">
Select Spirit: <select name="spirit">
<option>rail</option>
<option>call</option>
<option>premium</option>
</select><br>
Enter Spirit Amount (in ounces): <input type="number" name="spiritamount" value="1"><br><br>
<button>Add to receipt</button> or <button id="reset">Reset</button>
</form>
<p id="outputarea"></p>

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>

Arithmetic expressions in Javascript

I have studied java and php for many years and recently just started developing in JavaScript as well. Anyway a fairly noob question but can anyone work out why this application isn't showing displaying the interest when the button is clicked? I have been using w3schools website to learn from.
code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Interest Calculator</title>
</head>
<body>
<fieldset>
<legend>Interest Calculator</legend>
Enter amount: <input type="text" id="amount" ><br><br>
Interest rate: <input type="text" id="interest"><br><br>
Enter years: <input type="text" id="years"><br><br>
<button onclick="calculate()">Calculate</button>
</fieldset>
<p id="sum"></p>
<script>
function calculate(){
var amount = document.getElementById("amount").value;
var rate = document.getElementById("interest").value;
var years = document.getElementById("years").value;
var sum = amount(1+rate)^years;
var message = "Your total return will be: " + sum;
document.getElementById("sum").innerHTML = message;
}
</script>
</body>
</html>
Many thanks,
Adam
You need to explicitly specify *. It is not normal for 5(3) = 15 in JavaScript or any programming language. You need to explicitly specify 5*(3):
var sum = amount*(1+rate)^years;
Working Code
<fieldset>
<legend>Interest Calculator</legend>
Enter amount: <input type="text" id="amount" ><br><br>
Interest rate: <input type="text" id="interest"><br><br>
Enter years: <input type="text" id="years"><br><br>
<button onclick="calculate()">Calculate</button>
</fieldset>
<p id="sum"></p>
<script>
function calculate(){
var amount = document.getElementById("amount").value;
var rate = document.getElementById("interest").value;
var years = document.getElementById("years").value;
var sum = amount*(1+rate)^years;
var message = "Your total return will be: " + sum;
document.getElementById("sum").innerHTML = message;
}
</script>
Fiddle: http://jsbin.com/lovevazaxe
The OP uses the ^ operator and presumably wants to use the power-of operator.
In javascript the ^ operator refers to bitwise XOR - I don't think that's what the OP wants.
Instead, the power-of operation is done with the Math.pow() function.
So replace var sum = amount(1+rate)^years; with
var sum = Math.pow(amount*(1+rate),years)

Categories

Resources