How I get values updating/refreshing related input areas in Javascript? - javascript

I have a form and when I press the Try button it returns values for the 3rd and 6th input fields of the form according to the values entered in 1,2 and 5.6. Also, the 7th input field combines the 3rd and 6th results.
My question is how can I get the result values from input fields 3 and 6 without clicking the Try It button and also update the input field 7 without refreshing the page?
My code is in JSFiddle UPDATED !!
My Javascript are:
<script type="text/javascript">
function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
if (with_space===true) {
return string_one+'/'+string_two;
}
else {
return string_one+string_two;
}
}
function join_names() {
var input_name_first = document.getElementsByName('ht')[0].value;
var input_name_last = document.getElementsByName('ft')[0].value;
var input_name_full = document.getElementsByName('htft')[0];
var var_name_full = concatenate(input_name_first, input_name_last, true);
input_name_full.value = var_name_full;
}
</script>
<script type="text/javascript">
function myFunctionFt() {
var home = document.getElementById("home_score").value;
var away = document.getElementById("away_score").value;
var results;
if (home > away) {
results = "1";
} else if (home < away) {
results = "2";
} else if (home = away) {
results = "X";
}
document.getElementById("ft").value = results;
}
</script>
<script type="text/javascript">
function myFunctionHt() {
var home = document.getElementById("home_ht_score").value;
var away = document.getElementById("away_ht_score").value;
var results;
if (home > away) {
results = "1";
} else if (home < away) {
results = "2";
} else if (home = away) {
results = "X";
}
document.getElementById("ht").value = results;
}
</script>

I have removed all the previous answers from this answer and added a new answer in place. I have read your last comment and you said that my code was not working for the Home Team HT Score and Away Team HT Score. Well, I had made the logic to behave this way because it makes more sense to put the result in HT Result once both of the teams have played or in other words when we have both of the inputs. In sports, it rarely happens that only one team plays. Right. So outputting the result in HT result based on one of the inputs makes no sense. But if this is what you want, you simply have to change the logic from if (!input_home || !input_away) return; to if (!input_home && !input_away) return; and it will start working the way you want. Basically in the first logic statement with "||" we are saying unless both of the inputs are available don't out into HT result and in the second statement with && we are saying id doesn't matter if one of them is not present, just take whatever is present and output it in HT result. The same thing is happening for FT. You just have to change || to &&.
Here is the final working code:
//FT and HT Result//
let name_first = document.getElementById('ht');
let name_last = document.getElementById('ft');
let input_name_first = name_first.value;
let input_name_last = name_last.value;
//HT Home//
let home = document.getElementById("home_ht_score");
let away = document.getElementById("away_ht_score");
home_ht_score.addEventListener("input", myFunctionHt);
away_ht_score.addEventListener("input", myFunctionHt);
let input_away = away.value;
let input_home = home.value;
//FT Home//
let home_ft = document.getElementById("home_score");
let away_ft = document.getElementById("away_score");
home_score.addEventListener("input", myFunctionFt);
away_score.addEventListener("input", myFunctionFt);
let input_ft_away = away_ft.value;
let input_ft_home = home_ft.value;
function myFunctionHt() {
input_away = away.value;
input_home = home.value;
input_name_first = name_first.value;
input_name_last = name_last.value;
if (!input_home && !input_away) return;
var results = "";
if (input_home > input_away) {
results = "1";
} else if (input_home < input_away) {
results = "2";
} else if (input_home = input_away) {
results = "X";
}
document.getElementById("ht").value = results;
join_names();
}
function myFunctionFt() {
input_ft_away = away_ft.value;
input_ft_home = home_ft.value;
input_name_first = name_first.value;
input_name_last = name_last.value;
if (!input_ft_home && !input_ft_away) return;
var results = "";
if (input_ft_home > input_ft_away) {
results = "1";
} else if (input_ft_home < input_ft_away) {
results = "2";
} else if (input_ft_home = input_ft_away) {
results = "X";
}
document.getElementById("ft").value = results;
join_names();
}
function join_names() {
if (!input_name_first && !input_name_last) return;
let input_name_full = document.getElementsByName('htft')[0];
var var_name_full = concatenate(name_first.value, name_last.value, true);
input_name_full.value = var_name_full;
}
function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
if (with_space===true) {
return string_one+'/'+string_two;
}
else {
return string_one+string_two;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form class="form-group" action="addemp" method="post" onsubmit="return true" onClick="return false">
<table border="0" cellpadding="1">
<tbody>
<tr>
<td> <label class="form-label" style="color:blue" for="name">Home Team HT Score</label> </td>
<td> <input id="home_ht_score" name="home_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td> <label class="form-label" style="color:red" for="name">Away Team HT Score</label> </td>
<td> <input id="away_ht_score" name="away_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:green" for="name">HT Result</label> </td>
<td> <input id="ht" name="ht" type="text" class="form-control mb-3" oninput="join_names();" onpaste="join_names();" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:blue" for="name">Home FT Score</label> </td>
<td> <input id="home_score" name="home_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:red" for="name">Away FT Score</label> </td>
<td> <input id="away_score" name="away_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td> <label class="form-label" style="color:green" for="name">FT Result</label> </td>
<td> <input id="ft" name="ft" type="text" class="form-control mb-3" onchange="join_names();" onpaste="join_names();" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:green" for="name">HT/FT</label> </td>
<td> <input name="htft" type="text" class="form-control mb-3" style="width: 200px;"> </td>
</tr>
<tr>
<td> </td>
<td><button class="btn btn-primary mb-4" type="submit">Save Match Result</button> </td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

Related

Make a table row editable on click with Javascript

I want to make the row of my list editable after clicking on edit button. I set editablecontent= true for every row I want to change and added focus with onclick event but this works only for the first item. Could you suggest other ways of making the content of every row editable? I started recently to learn javascript so vanilla javascript would be better. Thanks!
Storedcontact = []
// Represent a contact
function convertToEntry(name, surname, phone, email) {
var obj = {
name: name,
surname: surname,
phone: phone,
email: email
};
return obj;
}
// add contacts
var form = document.getElementById("btn-submit");
form.addEventListener("click", function(ev) {
ev.preventDefault();
var name = document.getElementById("name").value;
var surname = document.getElementById("surname").value;
var number = document.getElementById("phone").value;
var mail = document.getElementById("email").value;
var duplicateFlag = false;
var entry = convertToEntry(name, surname, number, mail);
for (var i = 0; i < Storedcontact.length; i++) {
let entry = Storedcontact[i];
// this is duplicate
if (entry.name === name) {
alert("Duplicate") ;
duplicateFlag = true;
} else {
duplicateFlag = false;
}
}
// store and update ui onlz if name is not duplicate
if (duplicateFlag === false) {
Storedcontact.push(entry);
updateUI();
}
});
// showing contacts
function updateUI() {
var tbody = document.getElementById('entry-table');
// clearing the table
tbody.innerHTML = '';
var newHtml = '';
// looping the stored contacts
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable">${entry.name}</td>
<td contenteditable="true" id="editable">${entry.surname}</td>
<td contenteditable="true" id="editable">${entry.phone}</td>
<td contenteditable="true" id="editable">${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow();">Edit</button></td>
`;
tbody.appendChild(row);
function clearFields() {
document.getElementById("name").value = "";
document.getElementById("surname").value = "";
document.getElementById("phone").value = "";
document.getElementById("email").value = "";
}
clearFields();
}
}
function checkDuplicate (name) {
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
if (entry.name === name) {
alert("Duplicate")
} else {
}
}
}
function editHtmlTableRow (){
document.getElementById("editable").focus();
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<link rel="stylesheet" href="bootstrap.min (3).css">
<title>MyAddressBook</title>
</head>
<body>
<div class="container mt-4">
<h1 class="display-4 text-center">
My<span class="text-primary">Address</span>Book</h1>
<form id="address-form">
<div class="form-group"></div>
<label for="Name">Name</label>
<input type="text" id="name" class="form-control">
<div class="form-group"></div>
<label for="Surname">Surname</label>
<input type="text" id="surname" class="form-control">
<div class="form-group"></div>
<label for="Number">Number</label>
<input type="text" id="phone" class="form-control">
<div class="form-group"></div>
<label for="mail">E-mail</label>
<input type="text" id="email" class="form-control">
</div>
<br>
</br>
<input type="submit" value="Add contact" id="btn-submit" class="btn btn-primary btn-block container mt-4">
</form>
<table class="table table-striped">
<thread>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Number</th>
<th>E-mail</th>
<th></th>
</tr>
</thread>
<tbody id="entry-table"></tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
Assign a unique identifier such as your for loop counter to the Rows
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable"+i>${entry.name}</td>
<td contenteditable="true" id="editable"+i>${entry.surname}</td>
<td contenteditable="true" id="editable"+i>${entry.phone}</td>
<td contenteditable="true" id="editable"+i>${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow(${i});">Edit</button></td>
`;
tbody.appendChild(row);
}
and in your function
function editHtmlTableRow (i){
document.getElementById("editable"+i).focus();
}

How to get sum of onload inputs

HTML:
<table id="tab1">
<tr id="maint">
<td style="background-color:white;"></td>
<td>słowo klucz</td>
<td>ilość wynikow google</td>
</tr>
<tr>
<td id="maint">słowo klucz</td>
<td><input type="text" name="klucz" value="" required></td>
<td><input type="number" name="wyszkiwania" value="" onblur="sumX()" onkeyup="operatorf()" id="eq"required></td>
</tr>
<tr>
<td id="maint">słowo klucz</td>
<td><input type="text" name="klucz" value=""></td>
<td><input type="number" name="wyszkiwania" value="" onblur="sumX()" onkeyup="operatorf()" id="eq"required></td>
</tr>
</table>
JS:
var wejscie = document.getElementById('eq').value;
if ( wejscie <= 100000) {
var stawka13 = 59;
var stawka46 = stawka13*0.75;
var stawka710 = stawka46*0.55;
}
else {
var stawka13 = wejscie/100000*59;
if (stawka13 > 210) {
stawka13 = 210;
}
var stawka46 = stawka13*0.75;
var stawka710 = stawka46*0.55;
}
stawka13 = Math.round(stawka13).toFixed(2);
stawka46 = Math.round(stawka46).toFixed(2);
stawka710 = Math.round(stawka710).toFixed(2);
document.getElementById('sum13').innerHTML = "";
document.getElementById('sum46').innerHTML = "";
document.getElementById('sum710').innerHTML = "";
document.getElementById('sum13').innerHTML = " "+sum13+" zł";
document.getElementById('sum46').innerHTML = " "+sum46+" zł";
document.getElementById('sum710').innerHTML = " "+sum710+" zł";
I would like to get an sum of it but with this eq.
I try arr etc but aint work "properly" as I want.
My target is just sum all of it with all math in it.
I'm not allowed to add jq to it so it is impotant to stay on meta.

Issue replacing input value in array

I did an example about replacing the input value when the row is deleted but is not working (this is not a static example).
<script src="./edit_files/prototype.js" type="text/javascript"></script>
<script src="./edit_files/application.js" type="text/javascript"></script>
<div class="contact">
<table border="0">
<tr>
<td><select class="position_id" id="obj_client_contact_attributes__position_id" name="obj_client[contact_attributes][][position_id]"><option value="1" selected="selected">INTELIGENT</option><option value="2">OTHER</option></select></td>
<td><input class="should_change_value" id="obj_client_contact_attributes__phone_mail" name="obj_client[contact_attributes][][phone_mail]" type="text" value="cristianoronaldo#realmadrid.com"/></td>
<td>
DELETE
<input id="obj_client_contact_attributes__id" name="obj_client[contact_attributes][][id]" type="hidden" value="16594"/>
<input class="should_destroy" id="obj_client_contact_attributes__should_destroy" name="obj_client[contact_attributes][][should_destroy]" type="hidden"/>
</td>
</tr>
</table>
</div>
<div class="contact">
<table border="0">
<tr>
<td><select class="position_id" id="obj_client_contact_attributes__position_id" name="obj_client[contact_attributes][][position_id]"><option value="1" selected="selected">INTELIGENT</option><option value="2">OTHER</option></select></td>
<td><input class="should_change_value" id="obj_client_contact_attributes__phone_mail" name="obj_client[contact_attributes][][phone_mail]" type="text" value="ONLY THE INPUT WILL BE test#hotmail.com IF I CLICK ON DELETE"/></td>
<td>
DELETE
<input id="obj_client_contact_attributes__id" name="obj_client[contact_attributes][][id]" type="hidden" value="16594"/>
<input class="should_destroy" id="obj_client_contact_attributes__should_destroy" name="obj_client[contact_attributes][][should_destroy]" type="hidden"/>
</td>
</tr>
</table>
</div>
Here is the application.js file:
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
if (should_destroy) {
$(element).next('.should_destroy').value = 1;
}
$(element).up('.contact').hide();
}
I tried this code but only works if I remove the first row.
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
$('should_change_value').update("test#hotmail.com");
if (should_destroy) {
$(element).next('.should_destroy').value = 1;
}
$(element).up('.contact').hide();
}
Here is the live example in jsfiddle
Here is the example download on Github but is not replacing the input value correctly
Ok I got it, you want to change the input value when the row is deleted, so do this:
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
var element_text2 = $(element).up('.contact').down('.should_change_value',0);
element_text2.className = 'should_change_value';
element_text2.value = 'test#hotmail.com';
if (should_destroy) { $(element).next('.should_destroy').value = 1;}
$(element).up('.contact').hide();
}

Calculate on change for each row

I have an invoice form to generate a PDF. I want to calculate the inputs after the change of the value that the user fills in the form.
I can calculate the first row, but i want to (1) calculate each row and at the end to (2) calculate all the colums properly. For the first step just to the (1) and i will make the total calculation.
The problem is that i generate the rows with dynamic name and id because i post them in an array to the database. For this example the id is the same for every row of inputs.
PS: i cannot make .change work and i use $(document).on('change', '#qty', function (e) { calculateLine(); }); to trigger the calculation function for each input. I dont know why .change is not working as it support to, with latest jquery.
[invoice.php]
<script>
$(document).ready(function () {
$(document).on('change', '#qty', function (e) { calculateLine(); });
$(document).on('change', '#price', function (e) { calculateLine(); });
$(document).on('change', '#discount', function (e) { calculateLine(); });
$(document).on('change', '#discountPrice', function (e) { calculateLine(); });
});
</script>
[invoice.js]
function calculateLine() {
var qty = parseFloat($('#qty').val());
var price = parseFloat($('#price').val());
var discount = parseFloat($('#discount').val());
var discountPrice = parseFloat($('#discountPrice').val());
var vat = parseFloat($('#vat').val());
var netTotal = 0;
var total = 0;
var vatAmount = 0;
if (!qty && qty == 0) {
return;
}
if (!price && price == 0) {
return;
}
netTotal = qty * price;
if ((!discount || discount == 0) && discountPrice != 0) {
discount = (discountPrice / netTotal) * 100;
}
if ((!discountPrice || discountPrice == 0) && discount != 0) {
discountPrice = (netTotal / 100) * discount;
}
if (discountPrice != 0 && discount != 0) {
discountPrice = (netTotal / 100) * discount;
}
if ((!discount || discount == 0) && (!discountPrice || discountPrice == 0)) {
discountPrice = 0;
discount = 0;
}
total = netTotal - discountPrice;
if (!total || total == 0) {
total = 0;
}
vatAmount = (total / 100) * vat;
$('#total').val(total);
$('#discount').val(discount);
$('#discountPrice').val(discountPrice);
$('#vatAmount').val(vatAmount);
//calculateTotal();
}
[html]
<tr>
<td class="col-xs-0">
<input type="checkbox" name="selected[]" class="checkall">
</td>
<td class="col-xs-5">
<textarea type="text" name="invoice[item][{{j}}][description]" class="form-control description" rows="1" ></textarea>
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][unit]" class="form-control unit" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][qty]" class="form-control qty" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][price]" class="form-control price" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][discount]" class="form-control discount" value="" >
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][discountPrice]" class="form-control discountPrice" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][total]" class="form-control total" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][vat]" class="form-control vat" value="{{invcl_vat}}" readonly />
<input type="hidden" name="invoice[item][{{j}}][vatAmount]" class="form-control vatAmount" value="" readonly />
</td>
</tr>
You haven't shown your HTML, but it's clear from your question that you're using the same id (qty, etc.) on more than one element. You can't do that. Every id must be unique on the page. In this case, you'd probably use classes instead.
The general way that you do what you're talking about is indeed to use delegated event handling, then find the containing row, and use that as the starting point looking for descendant inputs using classes rather than ids:
$("selector-for-the-table").on("change", "input", function() {
// Get the row containing the input
var row = $(this).closest("tr");
// Get the values from _this row's_ inputs, using `row.find` to
// look only within this row
var qty = parseFloat(row.find('.qty').val());
var price = parseFloat(row.find('.price').val());
var discount = parseFloat(row.find('.discount').val());
var discountPrice = parseFloat(row.find('.discountPrice').val());
var vat = parseFloat(row.find('.vat').val());
// ...
});
I've also rooted that on the table, rather than document, so it only applies where appropriate.
Live (Simplified) Example:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="qty"></td>
<td><input type="text" class="price"></td>
<td><input type="text" class="total" disabled></td>
</tr>
<!-- ...and so on... -->
</tbody>
</table>
<script>
(function() {
"use strict";
$("table").on("change", "input", function() {
var row = $(this).closest("tr");
var qty = parseFloat(row.find(".qty").val());
var price = parseFloat(row.find(".price").val());
var total = qty * price;
row.find(".total").val(isNaN(total) ? "" : total);
});
})();
</script>
</body>
</html>
You've said before that the names are dynamic. Surely there is some characteristic of the fields you're trying to find that is consistent, or you can make them consistent. In the worst case (and I mean in the worst case), you could do something based on position — the first input in the row is row.find("input:eq(0)"), the second is row.find("input:eq(1)"), and so on.
Live Example Using eq:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text" disabled></td>
</tr>
<!-- ...and so on... -->
</tbody>
</table>
<script>
(function() {
"use strict";
$("table").on("change", "input", function() {
var row = $(this).closest("tr");
var qty = parseFloat(row.find("input:eq(0)").val());
var price = parseFloat(row.find("input:eq(1)").val());
var total = qty * price;
row.find("input:eq(2)").val(isNaN(total) ? "" : total);
});
})();
</script>
</body>
</html>
But avoid that if you possibly can, it's fragile — if you change the order of columns, you have to change your code.

JavaScript mortgage loan calculator returning "NaN" for monthly payment

I have been going insane over the last few days trying to figure this out, and I am at a complete loss as to what to do.
For an assignment I have to do for class, we have to analyse the following JavaScript code and correct the errors. I have managed to figure out most of it, but am stuck on this last part.
Whenever I click the "Calculate" button, it is returning "$NaN.undefined" for the monthly payment amount. I have gone over the code over and over again, and everything seems to match what it shows in my textbook, so I have no idea what I need to change to make it work properly.
I just started learning JavaScript a few days ago, so I am VERY new at this. Any help or guidance anyone could give me would be extremely appreciated.
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Make10-1 Oakwood Mortgage</title>
<script type="text/javascript">
<!--Hide from old browsers
var thisMsg=" ** See us for your auto loan financing needs!!! ** "
var beginPos=0
function scrollingMsg() {
msgForm.scrollingMsg.value=thisMsg.substring(beginPos,thisMsg.length)+thisMsg.substring(0,beginPos)
beginPos+=1
if (beginPos > thisMsg.length) {
beginPos=0
}
window.setTimeout("scrollingMsg()",200)
}
var salesAmt
var loanAmt
var loanRate
var loanYears
function valSaleDownAmt() {
var salesAmt=parseInt(LoanCalc.SaleAmt.value,10)
if (isNaN(salesAmt) || (salesAmt <=0)) {
alert("The sales amount is not a valid number!")
LoanCalc.SaleAmt.value = ""
LoanCalc.SaleAmt.focus()
}
else {
var DownPayment=parseFloat(LoanCalc.DownPmt.value)/100
if (isNaN(DownPayment) || (DownPayment <= 0) || DownPayment > 100) {
alert("The Down Payment Rate is not a valid number!")
LoanCalc.DownPmt.value = " "
LoanCalc.DownPmt.focus()
}
else {
var amtDown = salesAmt*DownPayment
var loanAmt = salesAmt-amtDown
LoanCalc.LoanAmt.value = dollarFormat(loanAmt.toFixed(2))
LoanCalc.Rate.focus()
}
}
}
function CalcLoanAmt() {
loanRate=parseFloat(LoanCalc.Rate.value)
if (isNaN(loanRate) || (loanRate <= 0)) {
alert("The interest rate is not a valid number!")
LoanCalc.Rate.value = ""
LoanCalc.Rate.focus()
}
else {
loanYears=parseInt(LoanCalc.Years.selectedIndex)
if (isNaN(loanYears) || (loanYears < 1)) {
alert("Please select a valid number of years from the list!")
LoanCalc.Years.selectedIndex = "0"
LoanCalc.Years.focus()
}
else {
var monthlyPmt = monthly(loanAmt,loanRate,loanYears)
LoanCalc.Payment.value=dollarFormat(monthlyPmt.toString())
}
}
}
function monthly(loanAmt,loanRate,loanYears) {
var Irate = loanRate/1200
var Pmts = loanYears*12
var Amnt = loanAmt * (Irate / (1 - (1 / Math.pow(1+Irate,Pmts))))
return Amnt.toFixed(2)
}
function dollarFormat(valuein) {
var formatValue = ""
var formatDollars = ""
formatAmt = valuein.split(".",2)
var dollars = formatAmt[0]
var dollarLen = dollars.length
if (dollarLen > 3) {
while (dollarLen > 0) {
tempDollars = dollars.substring(dollarLen - 3,dollarLen)
if (tempDollars.length == 3) {
formatDollars = "," + tempDollars + formatDollars
dollarLen = dollarLen - 3
} else {
formatDollars = tempDollars + formatDollars
dollarLen = 0
}
}
if (formatDollars.substring(0,1) == ",")
dollars = formatDollars.substring(1,formatDollars.length)
else
dollars = formatDollars
}
var cents = formatAmt[1]
var formatValue="$"+dollars+"."+cents
return formatValue
}
function popUpAd() {
open("make10-1notice.html","noticeWin","width=520,height=270")
}
function lastModified() {
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
displayDateLast.innerHTML="<span style='font-family:Arial, Helvetica, sans-serif; font-size:9px; font-weight:bold'>This document was last modified "+lastModDate+"</span>"
}
//-->
</script>
<style type="text/css">
<!--
body {
background-image: url(financial_symbol.jpg);
}
-->
</style>
</head>
<body onload="scrollingMsg(); popUpAd(); lastModified()">
<div align="center">
<p align="center"><img src="make10-1banner.jpg" width="750" height="120" alt="banner" /></p>
<form id="msgForm" action="">
<p style="text-align:center"><input type="text" name="scrollingMsg" size="25" /></p>
</form>
</div>
<div style="font-family:Arial, Helvetica, sans-serif">
<h3 align="center">Home Loan Payment Calculator</h3>
<form id="LoanCalc" action="">
<table width="346" align="center" cellspacing="3">
<tr>
<td align="right">
<span style="color:#cc0000">*</span>Sale Price:
</td>
<td><input type="text" name="SaleAmt" id="SaleAmt" size="9" /></td>
</tr>
<tr>
<td align="right">
<span style="color:#cc0000">*</span> Down Payment as a percent
</td>
<td><input name="DownPmt" type="text" id="DownPmt" size="4" onblur="valSaleDownAmt()" />
%</td>
</tr>
<tr>
<td align="right">
<span style="color:#cc0000">*</span> Interest Rate (e.g. 5.9):
</td>
<td><input type="text" name="Rate" id="Rate" size="4" /> %
</td>
</tr>
<tr>
<td align="right">
<span style="color:#cc0000">*</span> Select Number of Years:
</td>
<td><select name="Years" id="Years">
<option selected="selected">Select Years</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="40">40</option>
</select></td>
</tr>
<tr>
<td align="right">
<input name="button" type="button" value="Calculate" onclick="CalcLoanAmt()" />
</td>
<td>
<input name="Reset" type="reset" />
</td>
</tr>
<tr>
<td align="right">
<span style="color:#cc0000">*</span> Loan Amount
</td>
<td>
<input name="LoanAmt" type="text" id="LoanAmt" size="9" />
</td>
</tr>
<tr>
<td align="right">
<span style="font-weight:bolder">Monthly Payment</span>:
</td>
<td><input type="text" name="Payment" id="Payment" value=" " size="12" /></td>
</tr>
</table>
<p style="color:#cc0000; text-align:center">* Indicates a required field.</p>
</form>
</div>
<div id="displayDateLast" style="margin-left:5%">
</div>
</body>
</html>
I've made some changes in two of your functions, and rest of the functions and html are fine. And it worked, please check it:-
function valSaleDownAmt() {
var saleAmtInput = document.getElementById("SaleAmt"),
salesAmt=parseInt(saleAmtInput.value,10),
downPaymentInput = document.getElementById('DownPmt'),
DownPayment=parseFloat(downPaymentInput.value)/100,
loanRateInput = document.getElementById('Rate'),
loanRate=parseFloat(loanRateInput.value),
loanYearsInput = document.getElementById('Years'),
loanYears=parseInt(loanYearsInput.value);
if (isNaN(salesAmt) || (salesAmt <=0)) {
alert("The sales amount is not a valid number!")
saleAmtInput.value = ""
saleAmtInput.focus()
}
else if (isNaN(DownPayment) || (DownPayment <= 0) || DownPayment > 100) {
alert("The Down Payment Rate is not a valid number!")
downPaymentInput.value = " "
downPaymentInput.focus()
} else if (isNaN(loanRate) || (loanRate <= 0)) {
alert("The interest rate is not a valid number!")
loanRateInput.value = ""
loanRateInput.focus()
} else if (isNaN(loanYears) || (loanYears < 1)) {
alert("Please select a valid number of years from the list!")
}
else {
CalcLoanAmt(salesAmt,DownPayment,loanRate,loanYears);
}
}
function CalcLoanAmt(salesAmt,DownPayment,loanRate,loanYears) {
var amtDown = salesAmt*DownPayment,
loanAmt = salesAmt-amtDown,
monthlyPmt = monthly(loanAmt,loanRate,loanYears);
document.getElementById('Payment').value=dollarFormat(monthlyPmt.toString());
document.getElementById('LoanAmt').value = loanAmt;
}
That means, no need of the global variables like:-
var salesAmt
var loanAmt
var loanRate
var loanYears
You can remove this variables.
And you have to modify in two places in your html:-
One is:-
<tr>
<td align="right">
<span style="color:#cc0000">*</span> Down Payment as a percent
</td>
<td><input name="DownPmt" type="text" id="DownPmt" size="4" />
%</td>
</tr>
That means, you have to remove the function call on blur of the input box.
And the second is:-
<tr>
<td align="right">
<input name="button" type="button" value="Calculate" onclick="valSaleDownAmt()" />
</td>
<td>
<input name="Reset" type="reset" />
</td>
</tr>
That means you've to call the function valSaleDownAmt instead of the function CalcLoanAmt, on click on the calculate button.
The functionality of the previous code was same, but that would raise some issue in certain case, so i think it is more proper code. Try it.
A great opportunity to learn to use the debugger to step through your code. Add a couple of breakpoints in your functions that calculate the values and set a watch on the variables that are used to calculate the monthly payment and determine where they start returning an invalid value. You'll find the offending code in no time :)
You can read about the debugger for Chrome at https://developer.chrome.com/devtools/docs/javascript-debugging. There is also a decent introductory video at https://www.youtube.com/watch?v=htZAU7FM7GI.
Also, although not technically required, you should be ending your statements with a semi-colon. If you don't know all of the various statement rules for Javascript, leaving out the semi-colons can have unexpected results.
I think Bill has the best "answer". But I think in this particular example, you've got loanAmt defined in 2 places (var loanAmt).
I think you don't want it defined in the 2nd place (the local variable).
When CalcLoadAmount calls Monthly right now, the value of `loadAmt" isn't defined. I tried removing the 2nd variable declaration, and it might be the fix you need....
function valSaleDownAmt() {
var salesAmt=parseInt(LoanCalc.SaleAmt.value,10)
if (isNaN(salesAmt) || (salesAmt <=0)) {
alert("The sales amount is not a valid number!")
LoanCalc.SaleAmt.value = ""
LoanCalc.SaleAmt.focus()
}
else {
var DownPayment=parseFloat(LoanCalc.DownPmt.value)/100
if (isNaN(DownPayment) || (DownPayment <= 0) || DownPayment > 100) {
alert("The Down Payment Rate is not a valid number!")
LoanCalc.DownPmt.value = " "
LoanCalc.DownPmt.focus()
}
else {
var amtDown = salesAmt*DownPayment
//
// THIS IS THE LINE I CHANGED RIGHT BELOW THIS COMMENT**
//
loanAmt = salesAmt-amtDown
LoanCalc.LoanAmt.value = dollarFormat(loanAmt.toFixed(2))
LoanCalc.Rate.focus()
}
}
}
The problem has to do with the loanAmt variable as Brad Parks mentioned (it won't let me comment). If you add the below code to the beginning of the CalcLoanAmt(), the function will work. Although there are probably better ways of doing this, this code will fix it. Good luck!
loanAmt=parseInt(LoanCalc.SaleAmt.value,10) - (parseFloat(LoanCalc.DownPmt.value)/100)
I think the problem arises because your values remain undefined throughout. At the top of your script where your variables are declared, there are no default values given. Try giving them default values of 0. You shouldn't get undefined anymore. This won't solve your problem entirely but it's a good start. Also you should try making the variables global by putting this before the variables. So for the variables at the top do
this.salesAmt = 0
this.loanAmt = 0
this.loanRate = 0
this.loanYears = 0
and everywhere they appear in your code put this before them.

Categories

Resources