Submit button not working unless change input - javascript

I have a form calculator, when customer submit the form(input.php), it will open another page display the results(output.php target _blank). However, when they want to use the same page(input.php) to get the result again, the submit button not working anymore, unless they change some value in the input field, and for the drop down menu, the submit button won't work, even you changed the drop down value.
Can someone please help me to fix the problems? thanks. I just want the button enabled all the time, here is the partially code from input.php.
<form name="form1" action="output.php" method="post" target="_blank">
<table id="distax" width="750">
<th colspan="6">F. Discount & Taxes</th>
<tr>
<td width="120"><b><input type="radio" name="discountmu" id="disc" value="-" />Discount (-)<br /> <input type="radio" name="discountmu" id="mu" value="+" />Markup (+)</b></td>
<td width="80">% <input type="text" name="discmuv" size="3" value="0"></td>
<td width="120"><b>2. Tax Goods:</b></td>
<td width="80">% <input type="text" name="txgood" size="3" value="0" onkeyup="data_change(this);"></td>
<td width="120"><b>3. Tax Services:</b><br />(for items in G)</td>
<td width="*">% <input type="text" name="txservice" size="3" value="0" onkeyup="data_change(this);"></td>
</tr>
<table id="extra" width="750">
<th colspan="6">E. Extras</th>
<tr>
<td width="170"><b>1. Extra railing (total):</b></td>
<td width="70"><input type="text" name="extrail" size="2" value="0" onkeyup="data_change(this);">ft</td>
<td width="110"><b>2. Custom Color: </b></td>
<td width="*"><select size="1" value="<?=$_SESSION['name']?> " name="R4" id="R4" onchange="showme()">
<option selected value="noSS">Sand Stone (Ral 1019)</option>
<option value="noEW">Euro White (Ral 9010)</option>
<option value="noQG">Quartz Grey (Ral 8014)</option>
<option value="noJB">Java Brown (Ral 8014)</option>
<option value="yes">Custom</option>
</select>
<input type="text" id="color1other" name="color1other" style=" position:relative;display:none;" Size=20 value="enter custom color here">
</td>
</tr>
<tr>
<td width="170"> <b>3. Height adjustment [ft // cm]:</b></td>
<td width="*">
<select size="1" name="D8">
<option value="1.125">+2'6" // +76cm</option>
<option value="1.1">+2'0" // +61cm</option>
<option value="1.075">+1'6" // +46cm</option>
<option value="1.05">+1'0" // +30cm</option>
<option value="1.025">+0'6" // +15cm</option>
<option selected value="1">0</option>
<option value="0.985">-0'6" // -15cm</option>
<option value="0.97">-1'0" // -30cm</option>
<option value="0.955">-1'6" // -46cm</option>
<option value="0.94">-2'0" // -61cm</option>
<option value="0.925">-2'6" // -76cm</option>
<option value="0.91">-3'0" // -91cm</option>
</select>
</td>
<td width="110"><b>4. Freight (Sea/Land/Air): </b></td>
<td width="*">
<input type="text" id="freight" name="freight" Size=12 value="0"><b>USD</b>
</td>
</tr>
<input type="Submit" Value="Get your quote"> as
<input type="radio" value="detail" checked name="report">Dealer <input type="radio" name="report" value="short"> Client version in English
</form>
thanks for the reply, here is the code for the javascript, didn't see anything related to the submit button
//Date: 05/27/2009 Edited by EG
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
var val3=document.form1.load.value;
//Date: 07/27/2009 Edited by EG
//self.location=self.location + '&cat=' + val + '&load=' + val3;
//self.location='webcalc_input.php?PHPSESSID=' + ssidjs + '&cat=' + val + '&load=' + val3;
self.location='webcalc_input.php?cat=' + val + '&load=' + val3;
}
function reload3(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
var val2=form.subcat.options[form.subcat.options.selectedIndex].value;
var val3=document.form1.load.value;
//Date: 07/27/2009 Edited by EG
self.location= 'webcalc_input.php?cat=' + val + '&cat3=' + val2 + '&load=' + val3;
//self.location='webcalc_input.php?PHPSESSID=' + ssidjs + '&cat=' + val + '&cat3=' + val2 + '&load=' + val3;
}
function data_change(field) {
var check = true;
var value = field.value; //get characters
//check that all characters are digits, ., -, or ""
for (var i = 0; i < field.value.length; ++i) {
var new_key = value.charAt(i); //cycle through characters
if (((new_key < "0") || (new_key > "9")) && !(new_key == "") && (new_key != ".")) { //Included . to enable decimal entry
check = false;
break;
}
}
//apply appropriate colour based on value
if (!check) {
field.style.backgroundColor = "red";
}
else {
field.style.backgroundColor = "white";
}
}
function validateEmpty(fld) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "The required field has not been filled in.\n"
} else {
fld.style.background = 'White';
}
return error;
}

The text input contains a javascript function which you don't show in your code called data_change(). If I understand the question, its likely that that function is disabling the submit button and enabling it when the text changes. This is only an assumption without seeing your javascript code.
enter code here
Find the definition of the data_change() function and look for something relating to the submit button and comment it out.
You may remove the onkeyup="data_change(this);" from the <input> tag, but that could break other functionality!

Related

How to add the content of a textarea to the body of an email

Hi there: I've created a form in html with a table using select to choose between options. One option is "Other" which generates a new text area input field. Once the form has been completed the user can email it to themselves. I can get this to work for all the select options except the new 'Other" category. Instead of adding the new text to the email body it states "[object HTMLTableCellElement]". I have been trying to get this to work but have been unable to solve it or find an answer that helps me - as a relative newbie to coding I can't help thinking I'm missing something obvious...any help or suggestions would be great, thanks
`
Email new input
<form action="#" method="post" id="myForm">
<table id="myTable">
<tr>
<td><select name="variableList" id="variableList" class="select">
<option value="" disabled selected>Please choose...</option>
<option value="Var 1">Var 1</option>
<option value="Var 2">Var 2</option>
<option value="Var 3">Var 3</option>
<option value="Other">Other...</option>
</select></td>
</tr>
<tr>
<td id="newVariable"></td>
</tr>
<tr>
<td><input type="email" name="email" id="emailID" placeholder="Your email address..."></td>
</tr>
<tr>
<td><button type="button" class="buttons" onclick="sendEmail()" id="sendEmail()">Email</button></td>
</tr>
</table>
</form>`
And this is the javascript:
document.getElementById("variableList").addEventListener("change", generateTxtBox);
var x = 1;
function generateTxtBox(){
//Create new input textarea if "Other" is selceted from list of options
if (x==1 && document.getElementById('variableList').value == "Other") {
var input = document.createElement("input");
input.setAttribute('type', 'textarea');
input.setAttribute('placeholder', 'Your new variable...');
var parent = document.getElementById("newVariable");
parent.appendChild(input);
x += 1;
}
}
function sendEmail(){
var email = document.getElementById("emailID").value;
var subject = "Email variables";
var variableList = document.getElementById("variableList").value;
document.getElementById("newVariable").addEventListener("change", getText);
function getText(){
document.getElementById("newVariable").textContent = newVariable;
}
if (document.getElementById('variableList').value == "Other"){
window.location = "mailto:" + email + "?subject=" + subject + "&body=" + newVariable;
} else {
window.location = "mailto:" + email + "?subject=" + subject + "&body=" + variableList;
}
}
Assignments work like this: variable = [new value];
Next, you're adding an event listener right before "sending" the email, meaning the function you're setting as handler is never run. Even if it did run, the order is wrong.
Finally, newVariable is actually the id of the <td> you have, which means you're adding a textual representation of the table cell as body to the email link.
document.getElementById("variableList").addEventListener("change", txtBox);
function txtBox() {
// show textarea if "Other" is selected from list of options
document.getElementById("txtBoxRow").style.display = this.value == "Other" ? "table-row" : "none";
}
function sendEmail() {
var email = document.getElementById("emailID").value;
var subject = "Email variables";
var variableList = document.getElementById("variableList").value;
var body = variableList == "Other" ? document.getElementById("newVariable").value : variableList;
window.location = "mailto:" + email + "?subject=" + subject + "&body=" + body;
}
#txtBoxRow {
display: none
}
<table id="myTable">
<tbody>
<tr>
<td>
<select id="variableList" class="select">
<option value="" disabled selected>Please choose...</option>
<option>Var 1</option>
<option>Var 2</option>
<option>Var 3</option>
<option value="Other">Other...</option>
</select>
</td>
</tr>
<tr id="txtBoxRow">
<td>
<textarea id="newVariable"></textarea>
</td>
</tr>
<tr>
<td>
<input type="email" name="email" id="emailID" placeholder="Your email address...">
</td>
</tr>
<tr>
<td>
<button class="buttons" onclick="sendEmail()">Email</button>
</td>
</tr>
</tbody>
</table>

Why the form submission is possible even after form fields are empty?

Here is the HTML
<form action="../phpFiles/reportCalorie.php" method="post"
onsubmit="return calculateCalorie()" name="bmiform">
<select name="activity" >
<option value="">Select any activity</option>
<option value="1">baseball</option>
<option value="2">basketball</option>
<option value="3">jogging</option>
<option value="4">walking</option>
<option value="5">Cycling</option>
<option value="6">Running</option>
<option value="7">Swimming</option>
<option value="8">Handball</option>
<option value="9">Cricket</option>
<option value="10">Football</option>
</select>
</td>
</tr>
<tr>
<td><h4>How many minutes?</h4></td>
<td>
<input type="number" name="minutes" size="5px"/>
minutes
</td>
</tr>
<tr>
<td><h4>Enter your weight</h4></td>
<td>
<input type="text" name="weight" size="5px"/>
KG
</td>
</tr>
<tr>
<td><h4>Enter your Age</h4></td>
<td>
<input type="text" name="age" size="5px"/>
Years
</td>
</tr>
<tr>
<td><h4>Enter your height</h4></td>
<td>
<input type="text" name="feet" size="5px"/>
FEET
<input type="text" name="inches" size="5px"/>
inches
</td>
</tr>
<tr>
<td colspan="2">
<input class="button1" type="submit" name="calculate"
value="Calculate" title="calculate" onclick="calculateCalorie()"/>
<br/><br/>
</form>
Here is the Javascript
<script type="text/javascript">
function calculateCalorie()
{
if(validate())
{
var minutes=+document.bmiform.minutes.value;
var weight=+document.bmiform.weight.value;
return true
}
else
{
return false;
}
}
function validate()
{
var age = document.bmiform.age.value;
var feet = document.bmiform.feet.value;
var inches = document.bmiform.inches.value;
var weight = document.bmiform.weight.value;
var minutes= document.bmiform.minutes.value;
if(age =="" || feet=="" || inches=="" || weight=="" || minutes=="")
{
alert("Your fields are empty");
return false
}
else if(isNaN(age) || isNaN(feet) || isNaN(inches) ||
isNaN(weight) isNaN(minutes) )
{
alert("Please enter valid input")
return false;
}
else{
return true;
}
}
</script>
I do not understand that even i left the field empty why it accepting the form and direct me to other page. please if anything is wrong just let me know? I would greatly appreciated any help.
There are 2 minor issues with the code, one being the cause of the error. The first is that there's a syntax error in the isNaN check which should be changed to isNaN(weight) || isNaN(minutes).
Second, the <input ... has an onclick listener in addition to your form's onsubmit listener, which runs the validation twice and could cause problems later on.
(Note that I changed the alert into console.log, so the snippet would work)
function calculateCalorie()
{
if(validate())
{
var minutes=+document.bmiform.minutes.value;
var weight=+document.bmiform.weight.value;
console.log('submitting');
return true
}
else
{
return false;
}
}
function validate()
{
var age = document.bmiform.age.value;
var feet = document.bmiform.feet.value;
var inches = document.bmiform.inches.value;
var weight = document.bmiform.weight.value;
var minutes= document.bmiform.minutes.value;
if(age =="" || feet=="" || inches=="" || weight=="" || minutes=="")
{
console.log("Your fields are empty");
return false;
}
else if(isNaN(age) || isNaN(feet) || isNaN(inches) ||
isNaN(weight) || isNaN(minutes) )
{
console.log("Please enter valid input")
return false;
}
else{
return true;
}
}
<form action="../phpFiles/reportCalorie.php" method="post"
onsubmit="return calculateCalorie()" name="bmiform">
<select name="activity" >
<option value="">Select any activity</option>
<option value="1">baseball</option>
<option value="2">basketball</option>
<option value="3">jogging</option>
<option value="4">walking</option>
<option value="5">Cycling</option>
<option value="6">Running</option>
<option value="7">Swimming</option>
<option value="8">Handball</option>
<option value="9">Cricket</option>
<option value="10">Football</option>
</select>
</td>
</tr>
<tr>
<td><h4>How many minutes?</h4></td>
<td>
<input type="number" name="minutes" size="5px"/>
minutes
</td>
</tr>
<tr>
<td><h4>Enter your weight</h4></td>
<td>
<input type="text" name="weight" size="5px"/>
KG
</td>
</tr>
<tr>
<td><h4>Enter your Age</h4></td>
<td>
<input type="text" name="age" size="5px"/>
Years
</td>
</tr>
<tr>
<td><h4>Enter your height</h4></td>
<td>
<input type="text" name="feet" size="5px"/>
FEET
<input type="text" name="inches" size="5px"/>
inches
</td>
</tr>
<tr>
<td colspan="2">
<input class="button1" type="submit" name="calculate"
value="Calculate" title="calculate" />
<br/><br/>
</form>
else if(isNaN(age) || isNaN(feet) || isNaN(inches) ||
isNaN(weight) isNaN(minutes) )
You`ve missed "||" operator here. It triggers a syntax error, which fails further javascript execution.
You have an error in your code your missing an || operator
else if(isNaN(age) || isNaN(feet) || isNaN(inches) ||
isNaN(weight) || isNaN(minutes) )
{
alert("Please enter valid input")
return false;
}
You should also call preventDefault to prevent the default form.
function customSubmitFunction(evt) {
evt.preventDefault();
someBug();
return false;
}
In this case, even with the bug the form won't submit!

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.

Display text with conditions on dropdown [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am updating my previous Question:
User has to enter the amounts in text boxes: amt1, amt2, amt3
If they are selecting the option to pay 'Self' value 'S' and they need an Advance payment 'ad' as Yes 'y' then the text box adv1 should display a sum of amt1 + amt2 + amt 3 + $750.
In any other case the value in adv1 should be a 0.00 and of course the text box totalAmt should have the sum always of the amounts always.
I have tried the javascript to get the values of the options onChange and try to evaluate.
However values are not been passed on.
HTML
<table width="800" border="1" cellspacing="0" cellpadding="0">
<tr>
<th>Estimated Travel Cost</th>
<th>AED</th>
<td>
<input name="total" type="text" id "totalAmt"value="" readonly="true" style="text-align:center"/>
</td>
</tr>
<tr>
<th>Amount (AED)</th>
<th>Arranged By</th>
</tr>
<tr>
<td>Arrival (incl Taxes)</td>
<td>
<input name="amt1" id="amt1" type="text" value="0" style="text-align:center"/>
</td>
<td>
<select name = "drop1" id = "str" onChange="updateTextVal()">
<option value="S">Self</option>
<option value="C">Company</option>
</select>
</td>
</tr>
<tr>
<td>Local Travel</td>
<td>
<input name="amt2" type="text" value="" style="text-align:center"/>
</td>
<td>
<select name="drop2">
<option>Self</option>
<option>Company</option>
</select>
</td>
</tr>
<tr>
<td>Accomodation</td>
<td>
<input name="amt3" type="text" value="" style="text-align:center"/>
</td>
<td>
<select name="drop3">
<option>Self</option>
<option>Company</option>
</select>
</td>
</tr>
<td>Estimated Total Cost</td>
<td>
<input name="amt6" type="text" value="" style="text-align:center" />
</td>
<td>
<select name="drop6">
<option>Self</option>
<option>Company</option>
</select>
</td>
</tr>
<tr>
<td>Advance Required</td>
<td>
<select name="advReq" id="ad">
<option value="n">No</option>
<option value="y">Yes</option>
</select>
</td>
<td>
<input name="adv1" type="text" id="adv1" value="0" readonly="readonly" style="text-align:center"/>
</td>
</tr>
</table>
JavaScript
<script>
function updateText() {
var str = this.value;
var $vel = parseInt(document.getElementById("amt1"));
var $el = document.getElementById("adv1");
var val = document.getElementById('ad').value;
var $eval = document.getElementById('str').value;
if(val == 'y'){
if($eval == 's'){
$el.value = "750" + $vel;
} else {
$el.value = "0";
}
}
}
</script>
Html:
<table>
<tr>
<td><input name="amt1" id="txtAmt" type="text" value="" align="left" style="text-align:center" /></td>
<td><select name = "drop1" id="sc"><option value="S">Self</option><option value="C">Company</option></select></td>
</tr>
<tr>
<td>Advance Required</td>
<td><select name="advReq" id="ad">
<option value="y">Yes</option>
<option value="n">No</option>
</select>
</td>
<td><input id='re' name="adv1" type="text" readonly="readonly" value="" /></td>
</tr>
</table>
Javascript
document.getElementById('txtAmt').onkeyup = function(){
var txtV = parseInt(this.value);
var re = document.getElementById('re');
var ad = document.getElementById('ad').value;
var sc = document.getElementById('sc').value;
if(ad == 'y'){
// Yes in Advance Required
if(sc == 'S'){
// Self
re.value = 'Self: ' + (txtV + 750) + '$';
}
else{
re.value = 'Company: ' + (txtV + 750) + '$';
}
}
else{
// No in Advance Required
if(sc == 'S'){
re.value = 'Self: ' + '0.00';
}
else{
re.value = 'Company: ' + '0.00';
}
}
}
Here is demo
You should write a function that gathers the amt1, drop1 and advReq values and sets the appropriate value to adv1.
Then call it when the page is loaded OR the key is released in amt1 OR drop1/advReq select value is changed.
Don't forget that the value in amt1 might be left empty or not be an actual number.
Simply add a onClick function to each of the select elements as onclick="calculateAdvance()" defined as
function calculateAdvance()
{
if(document.forms[0].drop1.getSelectedValue == 'S' && document.forms[0].advReq.getSelectedValue == 'y')
{
var sum = eval(document.forms[0].amt1.value) + 750;
document.forsm[0].amt1.value = sum;
}
}
and change the HTML to
<td><select name = "drop1" onchange="calculateAdvance()"><option value="S">Self</option><option value="C">Company</option></select></td>
and
<select name="advReq" id="ad" onchange="calculateAdvance()">

Remove/delete part of hidden field value on button click

I am trying to build a form where users can add a course using select boxes.
When a course is added, it creates a new table row displaying the course to the user and also adds the course prefix and number (e.g. MATH120) to a hidden form field value. Finally, it adds a delete button.
The delete button should remove the table row AND the hidden input value that corresponds to the course being deleted.
Here's my jsfiddle: http://jsfiddle.net/MtJF2/10/
My script is deleting the row just fine, but its not removing the input value correctly. It's not throwing any errors. Sometimes I've noticed that it will delete the zero in the correct value (e.g. MATH120, becomes MATH12,). Any ideas what might be causing this?
HTML:
<script type="text/javascript">
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function($course, value) {
return value.replace($course, '');
});
}
</script>
<table width="80%" align="center">
<tr id="add-required-course">
<td><input type="button" value="+ Add a Required Course" class="MC-big-button" onclick="$('#course-menu').slideToggle()" /></td>
</tr>
</table>
<input type="hidden" id="required-courses" name="required-courses" value="null" />
<table id="course-menu" width="80%" align="center">
<tr>
<td>Select the course prefix:</td>
<td><select id="1" name="course-prefix">
<option value="MATH">MATH</option>
<option value="BIOL">BIOL</option>
</select>
</td>
</tr>
<tr>
<td>Select the course number:</td>
<td><select id="2" name="course-num">
<option value="101">101</option>
<option value="120">120</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Add this course" class="MC-big-button" id="save-course" />
</td>
</tr>
</table>
Javascript:
document.getElementById("save-course").onclick = buildCourse;
function buildCourse() {
var $coursePrefix = ($('#1').val());
var $courseNum = ($('#2').val());
var $course = $coursePrefix + $courseNum;
var $HTMLoutput = '<tr id="' + $course + '"><td>' + $course + '<input type="button" value="Delete" onclick="deleteCourse(\'' + $course + '\')" /></td></tr>';
var $VALUEoutput = ($('#required-courses').val());
if ($VALUEoutput == 'null') {
$VALUEoutput = $course + ',';
}
else {
$VALUEoutput = $VALUEoutput + $course + ',';
}
$('#course-menu').slideToggle();
$('#add-required-course').before($HTMLoutput);
$('#required-courses').val($VALUEoutput);
}
I found this question to be helpful, but I think my implementation is off.
You are replacing $course with a new value in the delete function at
$('#required-courses').val(function($course, value) {
// here it gets a new value which is wrong
Use it like this
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function(_, value) {
return value.replace($course, '');
});
}

Categories

Resources