Cant change values in text box with Javascript - javascript

I am trying to take numbers entered by a user and use them for calculating values, and then having these numbers displayed in the text boxes. When I submit the values, The text boxes to the right do not change. Any Ideas?
<!DOCTYPE html>
<html>
<head>
<title>Car Payment Calculator</title>
<style>
html, body {
margin:0;
padding:0;
}
#pagewidth {
max-width:9000em;
min-width:1000em;
}
#header {
position:relative;
height:150px;
background-color:#06F9FC;
width:100%;
display:block;
overflow:auto;
}
#maincol {
background-color: #FCC66C;
position: relative;
}
</style>
<HTA:APPLICATION ID="myCarPayment"
APPLICATIONNAME="Car Payment Calculator"
SYSMENU="yes"
BORDER="thin"
BORDERSTYLE="normal"
CAPTION="yes"
ICON=""
MAXIMIZEBUTTON="yes"
MINIMIZEBUTTON="yes"
SHOWINTASKBAR="yes"
SINGLEINSTANCE="yes"
SCROLL="no"
VERSION="1.0"
WINDOWSTATE="normal"/>
<script>
window.resizeTo(300,300);
function calculate() {
var years= document.forms.myForm.years.value;
var monthly= amount/(years*12);
var number= monthly/amount;
var form = document.forms.myForm;
var loanAmount = form.loanAmount.value;
var downPayment = '0';
var anualInterestRate = form.interestRate.value;
var years = form.years.value;
var monthRate = anualInterestRate/12;
var numberOfPayments = years * 12;
var Principal=loanAmount-downPayement;
var valueNumber = document.getElementById("numPay");
var vlaueMonthly = document.getElementById("monthlyPay");
valueNumber.value = numberOfPayments;
valueMonthly.value = monthly;
}
</script>
</head>
<body>
<div id="header">
<pre>
<p>This application will help you calculate car payments.<br/>
Just enter the information and hit Calculate!</p>
</pre>
</div>
<div id="maincol">
<pre>
<form name="myForm" action="" onsubmit="calculate()">
<table>
<tr>
<td>Loan Amount:</td><td> <input type="number" name="loanAmount"></td>
</tr>
<tr>
<td>Interest Rate:</td><td> <input type="number" name="interestRate"></td><td>Number of Payments:</td><td><input type="text" name="numberPayments" id="numPay" value="0"></td>
</tr>
<tr>
<td>Number of Years:</td><td> <input type="number" name="years"></td><td>Monthly Payment:</td><td><input type="text" name="monthlyPayments" id="monthlyPay" value="0"></td>
</tr>
<tr>
<td><input type="submit" value="Calculate"></td>
</tr>
</table>
</form>
</pre>
</div>
</body>
</html>

You are getting an error in your callback function calculate():
Uncaught ReferenceError: amount is not defined
You're using amount but you've not defined/declared it.
I'm not sure what the value of amount should be.

Also get the value from input and convert it into number by using parsetInt(), you need convert them into number before calculation.
var years = parseInt(document.forms.myForm.years.value, 10);
var loanAmount = parseInt(form.loanAmount.value, 10);
var valueNumber = parseInt(document.getElementById("numPay"), 10);
var vlaueMonthly = parseInt(document.getElementById("monthlyPay"), 10);

Related

Multiply output by inputs

I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>

JavaScript getElementById always returning null

I am trying to build a simple budget calculator, everytime I click my submit button I nothing happens. When I try to check my variable values in the console they show null, even after I have typed values in my input boxes. Can anyone tell me what I'm doing wrong? After looking through other questions on here I haven't been able to find an answer that relates to my issue.
<!DOCTYPE html>
<html>
<head>
<title>Budget Calculator</title>
<style>
input {display:block;}
#clear {float:left;}
#submit {float:left;}
</style>
<script type="text/javascript">
var kms = document.getElementById("kmTravelled");
var rent = document.getElementById("rentPerMonth");
var carCost = document.getElementById("carPayment");
var costPerTrip = (kms/12.75)*20;
var total = Math.round((costPerTrip + rent + carCost)*100)/100;
function calculate()
{
document.getElementById("calculator").innerHTML = total;
}
</script>
</head>
<body>
<form id="myForm")>
Km travelled per day: <input type="number" name="kmTravelled" />
Rent per month: <input type="number" name="rentPerMonth" />
Car payment per month: <input type="number" name="carPayment" />
</form>
<button id="submit" type="button" onclick="calculate();">
Submit
</button>
<button id="clear" type="clear">
Clear
</button>
<p id = "calculator">
</p>
<script>
calculate();
</script>
</body>
I suggest to use id attributes and move the parts for getting the values inside of the function, as well as getting value property and cast the string value to number for calculation.
function calculate() {
var kms = +document.getElementById("kmTravelled").value;
var rent = +document.getElementById("rentPerMonth").value;
var carCost = +document.getElementById("carPayment").value;
var costPerTrip = (kms / 12.75) * 20;
var total = Math.round((costPerTrip + rent + carCost) * 100) / 100;
document.getElementById("calculator").innerHTML = total;
}
input { display: block; }
#clear { float: left; }
#submit { float: left; }
<form id="myForm">
Km travelled per day: <input type="number" name="kmTravelled" id="kmTravelled"/> Rent per month: <input type="number" name="rentPerMonth" id="rentPerMonth" /> Car payment per month: <input type="number" name="carPayment" id="carPayment" />
</form>
<button id="submit" type="button" onclick="calculate();">Submit</button>
<button id="clear" type="clear">Clear</button>
<p id="calculator"></p>
You don't have no id's in you input's but you have name's instead so you could use name selector $('[name=""]') like :
var kms = document.querySelector("[name='kmTravelled']").value;
var rent = document.querySelector("[name='rentPerMonth']").value;
var carCost = document.querySelector("[name='carPayment']").value;
If you want really to use id's , just add them and the JS code could be :
var kms = document.querySelector("#kmTravelled").value;
var rent = document.querySelector("#rentPerMonth").value;
var carCost = document.querySelector("#carPayment").value;
NOTE : You should get just the value of the element not the whole object.
Hope this helps.
var kms = document.querySelector("[name='kmTravelled']").value;
var rent = document.querySelector("[name='rentPerMonth']").value;
var carCost = document.querySelector("[name='carPayment']").value;
var costPerTrip = (kms/12.75)*20;
var total = Math.round((costPerTrip + rent + carCost)*100)/100;
function calculate()
{
document.getElementById("calculator").innerHTML = total;
}
calculate();
input {
display:block;
}
#clear {
float:left;
}
#submit {
float:left;
}
<form id="myForm")>
Km travelled per day: <input type="number" name="kmTravelled" />
Rent per month: <input type="number" name="rentPerMonth" />
Car payment per month: <input type="number" name="carPayment" />
</form>
<button id="submit" type="button" onclick="calculate();">
Submit
</button>
<button id="clear" type="clear">
Clear
</button>
<p id = "calculator"></p>
I think you need to try getElementById('kmTravelled').
First, you have to give proper id in HTML tag. check your HTML tag, convert those name into id.
Now you have to slightly change your javascript code, if you look at your code you didn't assign any value to your variable. fix these problems and your code will run properly.

Converter boxes, How to make it both output boxes work?

I am doing a project of a converter. When I put a number in the number box, it shows up fine in the box2. But when I try to enter a number in box2, and it won't show the answer in box1. Can anyone help me? I don't know jquery and I am a starter of html and javascript. Hopefully, someone can help me. Thanks
function NumberToSquare(num)
{
var sqrt;
sqrt = Math.sqrt(num);
return sqrt;
}
function SquareToNumber(sqrt)
{
var num;
num = Math.pow(sqrt,2);
return num;
}
<html>
<head>
<title>Program Assignment 5</title>
<script type = text/javascript src = "calculate.js"> </script>
<script type="text/javascript">
function ConvertToSqrt()
//Assumes: Number contains a number
//Results: displays the square root in box2
{
num = parseFloat(document.getElementById('box1').value);
sqrt = NumberToSquare(num);
box2.value=sqrt;
}
function ConvertToNum()
//Assumes: Square contains a number of square root
//Results: displays the number in box1
{
sqrt = parseFloat(document.getElementById('box2').value);
num = SquareToNumber(sqrt);
box1.value=num;
}
</script>
</head>
<body>
<div style="border: solid; width: 300px; background-color: #83CAFF">
<table>
<th></th> <th>Square Root Calculation</th>
<tr>
<th>Enter Number:</th><th><input type="number" id="box1" value=""></th>
<tr>
<th>SquareRoot:</th><th><input type="number" id="box2" value=""></th>
<tr>
<th></th><th><input type="button" value="Calculate" onclick="ConvertToSqrt(); ConvertToNum();">
</table>
</div>
If it helps any, here's a quick sample. It's not pretty but you can take what pieces you need and use it with your own.
<html>
<head>
<title></title>
<script>
function calc(which) {
var newVal;
if (which == "sqrt") {
newVal = parseFloat(document.getElementById("num").value);
newVal = Math.sqrt(newVal);
}
else if (which == "num") {
newVal = parseFloat(document.getElementById("sqrt").value);
newVal = Math.pow(newVal, 2);
}
document.getElementById(which).value = newVal;
}
</script>
</head>
<body>
<div style="width:400px;padding:25px;display:inline-block;line-height:150%;background-color:#83CAFF;font-weight:bold;border:solid 1px black;">
<div style="width:200px;float:left;">
<label>Number:</label>
<br />
<label>SquareRoot:</label>
</div>
<div style="width:200px;float:right;">
<input type="number" id="num"/>
<br />
<input type="number" id="sqrt"/>
</div>
<button type="button" style="width:100%;" onclick="calc('sqrt');">Calc Sqrt</button>
<button type="button" style="width:100%;" onclick="calc('num');">Calc Num</button>
</div>
</body>
</html>

Can't set cookie value

Cookie values are not displayed for fname, production, prod From. Everytime returns "null null null". But the date of the last entry is displayed normally.
It was necessary to create and process cookie, storing the value of any of the form fields (fname, production, prodForm), which was introduced at the last attempt of filling and the date.
Is the problem in function setCookie? (Because I get the date of the last visit) Please help to fix it.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Medicines</title>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="formaFunctions.js"></script>
<script type="text/javascript" src="cookies.js"></script>
</head>
<body onload="checkCookie()">
<h2>Medicines</h2>
<div id="error"></div>
<br>
<form name="myForm"
action="http://10.12.53.159:8111/stud"
onsubmit="return validateForm()"
method="post">
<table border="2">
<tr>
<td>Name:</td>
<td><input type="text" name="fname"></td>
</tr>
<tr><td>Production:</td>
<td><input type="text" name="production"></td>
</tr>
<tr><td>Production form:</td>
<td><select name="prodForm">
<option>Powder</option>
<option>Tablets</option>
<option>Dragee</option>
<option>Mixture</option>
<option>Salve</option>
</select></td>
</tr>
</table>
<p><input type="submit" value="Find" /></p>
</form>
<div id="cookie"></div>
</body>
</html>
</code>
Javascript:
function setCookie(name,value,exdays){
var cookie_string = name+"="+escape(value);
if(exdays){
var exdate = new Date();
exdate.setTime(exdate.getTime()+(exdays*24*60*60*1000));
var expires = "; expires="+exdate.toGMTString();
}
document.cookie = cookie_string;
}
function getCookie(c_name){
var i,x,y, ARRcookies=document.cookie.split(';');
for(i=0; i<ARRcookies.length; i++){
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x = x.replace(/^\s+|\s+$/g,"");
if (x==c_name){
return unescape(y);
}
}
}
function checkCookie(){
var string;
var fname = getCookie("fname");
var production = getCookie("production");
var prodForm = getCookie("prodForm");
if(fname!=null&&fname!=""){
string = fname;
}
else{
setCookie("fname", fname, 30);
}
if(production!=null&&production!=""){
string += production;
}
else{
setCookie("production", production, 30);
}
if(prodForm!=null&&prodForm!=""){
string += prodForm;
}
else{
setCookie("prodForm", prodForm, 30);
}
string += getCookie("lastVisit");
document.getElementById('cookie').innerHTML = string;
setCookie("lastVisit",new Date().toLocaleString(),30);
}

Stuck trying to assign JS vars to hidden fields

I've been fighting with this for a couple of days now...need some guidance please.
I have pared down a much bigger form to a "sample" size to demonstrate what I am after.
The area in question is blocked off in a very recognizable area in the calcFees function.
I also tried to get fancy and have the vars self post to the form so they could be seen, but that does not work.
UPDATE: Here is a bit more info as to what I am running into.
//At this point the var regularfee is = 26.5
// (confirmed by console.log(regularfee);)
// I want to assign it to the hidden field with the id="regularfee"
// I have tried both of the following lines:
document.getElementById('regularfee').value=regularfee.value;
// console.log(document.getElementById('regularfee.value')); shows "null"
document.getElementById('regularfee').value=regularfee;
// console.log(document.getElementById('regularfee')); shows "[object HTMLDivElement]"
What am I doing wrong?
END OF UPDATE *****************************
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="multiForm" action="post.php" method="POST" id="app" name="app">
<div id="page1" class="page" style="visibility:visible;">
Name: <input type="text" size="40" name="name1" >
<br><br>
<table border="1" cellpadding="5" width="50%">
<tbody>
<tr>
<td align="center" colspan="3"><strong>Membership Classification</strong></td>
</tr>
<tr><td width="1000">
<input name="paymethod" type="radio" class="pay" id="paypal" value="paypal" />I would like to use PayPal   
<input name="paymethod" type="radio" class="pay" id="check" value="check" />I would like to pay by check
</td>
<td style="width:150px" align="right">Fee
</td>
<td style="width:150px">
</td></tr>
<tr>
<td><input name="memberclass" type="radio" class="membership" id="regular" value="regular"/> Regular Membership</td>
<td align="right"><div id=regularfee></td>
<td><div align="right" id=regselectedfee></td>
</tr>
<tr><td colspan="2" align="right">Total </td>
<td><div align="right" id=total>
</td></tr></tbody>
</table>
<input type="hidden" name="regularfee" id="regularfee" value="">
<input type="hidden" name="regselectedfee" id="regselectedfee" value="">
<input type="hidden" name="total" id="total" value="">
</form>
<br>
<input type="button" id="C1" value="Continue" onClick="showLayer('page2')">
</td></tr>
</table>
</div>
<div id="page2" class="page">
<b>Page 2
<br><br>
<input type="button" id="B1" value="Go Back" onClick="showLayer('page1')">
<input type="submit" name="submit" value="Click to see Vars" />
</div>
</form>
</body>
</html>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script language="JavaScript">
var paypalselected
var checkselected
var regularfee
var memberfee1
var total
$(function () {
function clearForm()
{
paypalselected = "0";
checkselected = "0";
regularfee = 0.0;
memberfee1 = 0.0;
total = 0.0;
$("#regselectedfee").text(memberfee1.toFixed(2));
$("#total").text(total.toFixed(2));
// clear all radio buttons
$("#regular").prop("checked", false );
}
function calcFees()
{
total = (memberfee1);
$("#total").text(total.toFixed(2));
// **********************************************************************************
// Here is where I want to plug in the 3 JS vars to the hidden fields
// regularfee, regselectedfee, total
// Here is what I've tried:
// vars are not getting plugged in
// If possible, I would like the vars to be plugged in dynamically
// just as the form is updateddynamically when user selects buttons
document.getElementById('regularfee').value=regularfee;
document.getElementById('regselectedfee').value=regselectedfee;
document.getElementById('total').value=total;
// **********************************************************************************
}
function selectPayment()
{
$(".pay").change(function () {
clearForm();
if ($("#paypal").prop("checked")) {
regularfee = 26.50;
$("#regularfee").text(regularfee.toFixed(2));
paypalselected = "1";
checkselected = "0";
}
if ($("#check").prop("checked")) {
regularfee = 25.0;
$("#regularfee").text(regularfee.toFixed(2));
checkselected = "1";
paypalselected = "0";
}
});
}
clearForm();
selectPayment();
//start of membership button selection
$(".membership").change(function () {
if (paypalselected == "1"){
if ($("#regular").prop("checked")) {
memberfee1 = 26.5;
$("#regselectedfee").text(memberfee1.toFixed(2));
calcFees();
}
} //end of paypalselected test
if (checkselected == "1"){
if ($("#regular").prop("checked")) {
memberfee1 = 25.0;
$("#regselectedfee").text(memberfee1.toFixed(2));
calcFees();
}
} //end of checkselected test
}); //end of $(".membership").change(function () {
});
//end of main function
var currentLayer = 'page1';
function showLayer(lyr){
hideLayer(currentLayer);
document.getElementById(lyr).style.visibility = 'visible';
currentLayer = lyr;
window.scrollTo(0,0);
}
function hideLayer(lyr){
document.getElementById(lyr).style.visibility = 'hidden';
}
</script>
<style>
body{
font: 10pt sans-serif;
}
.page{
position: absolute;
top: 10;
left: 100;
visibility: hidden;
}
p.small
{
line-height: 5px;
}
p.smalltext12
{
font-size:12px
}
</style>
You have 2 elements #total. Only the first is given a value:
document.getElementById('total').value = total;
Same for the others.
IDs must be unique to be useful.

Categories

Resources