Add Comma After Every Three Digits in Input Value After OnClick Event - javascript

I have a table/form that calculates monthly payments for a mortgage. When the calculate button is pressed, a JavaScript function will make a calculation based on the values of the inputs and set the value of that calculation inside of the Monthly Payment input. My problem is when the value is set for that input, the value gets displayed without commas. For instance, 1543 instead of 1,543. If anyone knows anyway to add commas into the Monthly Payment input that would be great. Here is a picture of the Mortgage Calculator with the Monthly Payment input outlined:
Here is the code for the mortgage calculator:
<form action="POST" name="myform">
<table border="1" bgcolor="#006666">
<tr>
<td align="center" colspan="2">
<script
language="JavaScript"><!--
function CarLoanCalculator()
{
form = document.myform
LoanAmount= form.LoanAmount.value
LoanAmount = LoanAmount.replace(/,/g, "");
parseInt(LoanAmount);
DownPayment= "0"
AnnualInterestRate = form.InterestRate.value/100
Years= form.NumberOfYears.value
MonthRate=AnnualInterestRate/12
NumPayments=Years*12
Prin=LoanAmount-DownPayment
MonthPayment=Math.floor((Prin*MonthRate)/(1-Math.pow((1+MonthRate),(-1*NumPayments)))*100)/100
commafy ("MonthPayment")
form.NumberOfPayments.value=NumPayments
form.MonthlyPayment.value=MonthPayment
}
// --></script>
<script type="text/javascript">
function format(input)
{
var nStr = input.value + '';
nStr = nStr.replace( /\,/g, "");
x = nStr.split( '.' );
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while ( rgx.test(x1) ) {
x1 = x1.replace( rgx, '$1' + ',' + '$2' );
}
input.value = x1 + x2;
}
</script>
<font color="#FFFFFF"
size="2" face="arial narrow"><b>Mortgage Calculator</b> <br>
Enter Your Details & Click the Calculate Button</font></td>
</tr>
<tr>
<td>
<table border="0" cellpadding="2">
<tr>
<td align="right"><font color="#FFFFFF"
size="2" face="arial narrow">Finance Amount $ </font></td>
<td><font color="#FFFFFF" size="2"
face="arial narrow">
<input type="text"
size="10" name="LoanAmount" value="30,000"
onBlur="CarLoanCalculator()" onkeyup="format(this)" onChange="CarLoanCalculator()">
<br>
</font></td>
</tr>
<tr>
<td align="right"><font color="#FFFFFF"
size="2" face="arial narrow">Annual Interest Rate </font></td>
<td><font color="#FFFFFF" size="2"
face="arial narrow">
<input type="text"
size="3" name="InterestRate" value="7.0"
onBlur="CarLoanCalculator()" onChange="CarLoanCalculator()">
% <br>
</font></td>
</tr>
<tr>
<td align="right"><font color="#FFFFFF"
size="2" face="arial narrow">Term of Mortgage</font></td>
<td><font color="#FFFFFF" size="2"
face="arial narrow">
<input type="text"
size="3" name="NumberOfYears" value="4"
onBlur="CarLoanCalculator()" onChange="CarLoanCalculator()">
Years<br>
</font></td>
<td><font color="#FFFFFF" size="2"
face="arial narrow">
<input type="button"
name="morgcal" value="Calculate"
language="JavaScript" onClick="CarLoanCalculator()">
</font></td>
</tr>
<tr>
<td colspan="3"><font color="#FFFFFF"></font></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table border="0" cellpadding="2">
<tr>
<td align="right"><font color="#FFFFFF"
size="2" face="arial narrow"> Number of Payments </font></td>
<td><font color="#FFFFFF" size="2"
face="arial narrow">
<input type="text"
size="7" name="NumberOfPayments">
<br>
</font></td>
</tr>
<tr>
<td align="right"><font color="#FFFFFF"
size="2" face="arial narrow">Monthly Payment $ </font></td>
<td><font color="#FFFFFF" size="2"
face="arial narrow">
<input type="text"
size="7" name="MonthlyPayment" id="test">
<br>
</font></td>
</tr>
<tr>
<td align="center" colspan="2"> </td>
</tr>
</table>
</td>
</tr>
</table>
<div align="center"></div>
</form>
Thank you for any help. All help is greatly appreciated.

The correct JavaScript code to add a comma after every three digits in the Monthly Payments input value for an onclick event would be:
<script
language="JavaScript"><!--
function CarLoanCalculator()
{
form = document.myform
LoanAmount= form.LoanAmount.value
LoanAmount = LoanAmount.replace(/,/g, "");
parseInt(LoanAmount);
DownPayment= "0"
AnnualInterestRate = form.InterestRate.value/100
Years= form.NumberOfYears.value
MonthRate=AnnualInterestRate/12
NumPayments=Years*12
Prin=LoanAmount-DownPayment
function ReplaceNumberWithCommas(yourNumber) {
MonthPayment=Math.floor((Prin*MonthRate)/(1-Math.pow((1+MonthRate),(-1*NumPayments)))*100)/100
yourNumber = MonthPayment
//Seperates the components of the number
var components = yourNumber.toString().split(".");
//Comma-fies the first part
components [0] = components [0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return components.join(".");
}
//Seperates the components of the number
form.NumberOfPayments.value=NumPayments
form.MonthlyPayment.value=ReplaceNumberWithCommas()
//Seperates the components of the number
}
// --></script>
Note: the code is a bit out of order in terms of neatness and perhaps the comments, but the JavaScript syntax is correct.

Related

Why is my code not returning a value for a future value payment?

Trying to create a Javascript for future value calculation. This is the code im using but it is not returning a value. Don't know where the code is wrong. Has user input investment, interest rate, monthly payment added, and terms. After that code how do I create a for loop to create an amortization schedule.
<body>
<form name="fv">
<table>
<tr><td colspan="3"><b>Enter Investment Information:</b></td></tr>
<tr>
<td>1)</td>
<td>Amount of the Investment (any currency):</td>
<td>
<input type="text" name="investment" size="12"
onchange="calculate();">
</td>
</tr>
<tr>
<td>2)</td>
<td>percentage rate of interest:</td>
<td>
<input type="text" name="interest" size="12"
onchange="calculate();">
</td>
</tr>
<tr>
<td>3)</td>
<td>Monthly Payment Amount:</td>
<td>
<input type="text" name="monthly" size="12"
onchange="calculate();">
</td>
</tr>
<tr>
<td>4)</td>
<td>Terms:</td>
<td>
<input type="text" name="terms" size="12"
onchange="calculate();">
</td>
</tr>
<tr>
<td colspan="3">
<input type="button" value="Calculate" onclick="calculate();">
</td>
</tr>
<tr>
<td colspan="3">
<b>Investment Information:</b>
</td>
</tr>
<tr>
<td>4)</td>
<td>Your Investment will be worth:</td>
<td><input type="text" name="payment" size="12"></td>
</tr>
</table>
</form>
<script language="JavaScript">function calculate() {
var investment = document.fv.investment.value;
var interest = document.fv.interest.value / 100 / 12;
var terms = document.fv.terms.value * 12;
var x = Math.pow(1 + interest, terms);
var monthly = (investment * x);
if (!isNaN(monthly) &&
(monthly != Number.POSITIVE_INFINITY) &&
(monthly != Number.NEGATIVE_INFINITY)) {
document.fv.payment.value = round(monthly);
}
else {
document.fv.payment.value = "";
}
}
function round(x) {
return Math.round(x * 100) / 100;
</script>
I don't know what exactly you meant but it return value into input you haven't closed round func and wrong type on script
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form name="fv">
<table>
<tr><td colspan="3"><b>Enter Investment Information:</b></td></tr>
<tr>
<td>1)</td>
<td>Amount of the Investment (any currency):</td>
<td>
<input type="text" name="investment" size="12"
onchange="calculate();">
</td>
</tr>
<tr>
<td>2)</td>
<td>percentage rate of interest:</td>
<td>
<input type="text" name="interest" size="12"
onchange="calculate();">
</td>
</tr>
<tr>
<td>3)</td>
<td>Monthly Payment Amount:</td>
<td>
<input type="text" name="monthly" size="12"
onchange="calculate();">
</td>
</tr>
<tr>
<td>4)</td>
<td>Terms:</td>
<td>
<input type="text" name="terms" size="12"
onchange="calculate();">
</td>
</tr>
<tr>
<td colspan="3">
<input type="button" value="Calculate" onclick="calculate();">
</td>
</tr>
<tr>
<td colspan="3">
<b>Investment Information:</b>
</td>
</tr>
<tr>
<td>4)</td>
<td>Your Investment will be worth:</td>
<td><input type="text" name="payment" size="12"></td>
</tr>
</table>
</form>
<script type="text/javascript">
function calculate() {
var investment = document.fv.investment.value;
var interest = document.fv.interest.value / 100 / 12;
var terms = document.fv.terms.value * 12;
var x = Math.pow(1 + interest, terms);
var monthly = (investment * x);
if (!isNaN(monthly) && (monthly !== Number.POSITIVE_INFINITY) &&
(monthly !== Number.NEGATIVE_INFINITY)) {
document.fv.payment.value = round(monthly);
}
else {
document.fv.payment.value = "";
}
}
function round(x) {
return Math.round(x * 100) / 100;
}
</script>
</body>
</html>

Do arithmetic calculations on Table elements

Hello and thank you in advance.
I have a table where some values prefilled (like 111.36) but when I try to do math with the numbers, or even display the number nothing happens.
Thank you for your assistance,
Marc (new at Javascript)
function calculate_it() {
window.alert("In function calculate_it");
var x = document.getElementByID("Numb01").value;
window.alert(x);
} //end function
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<TITLE>Javascript Table</TITLE>
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<h3>A demonstration of calculators</h3>
<table id="t01">
<caption>Chek this out!</caption>
<tr>
<th>Date</th>
<th>Number 1</th>
<th>Number 2</th>
<th>Number 3</th>
<th>Number 4</th>
</tr>
<tr>
<td>
<input type="text" id="Date01" value="WED21DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb01" value=111.36 size="5" />
</td>
<td>
<input type="number" id="Numb02" value=222.36 size="5" />
</td>
<td>
<input type="number" id="Numb03" value=333.36 size="5" />
</td>
<td>
<input type="number" id="Numb04" value=444.36 size="5" />
</td>
</tr>
<tr>
<td>
<input type="text" id="Date02" value="WED22DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb05" value=555.36 size="5" />
</td>
<td>
<input type="number" id="Numb06" value=666.36 size="5" />
</td>
<td>
<input type="number" id="Numb07" value=777.36 size="5" />
</td>
<td>
<input type="number" id="Numb08" value=888.36 size="5" />
</td>
</tr>
<TR>
<td height="20" ColSpan="5"></td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Multiply:</td>
<td>
<input type="text" id="ActionMulti" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Add:</td>
<td>
<input type="text" id="ActionAdd" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Percentage:</td>
<td>
<input type="text" id="ActionPercentage" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>----------</td>
<td>--------</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Sum:</td>
<td>
<input type="text" id="Sum" value="" size="5" />
</td>
</TR>
</table>
<br>
<p>Click the button to calculate the data</p>
<button type="button" onclick="calculate_it()">calculate_it</button>
</body>
</html>
Well, I guess you already read all the comments saying the same: It's getElementById not getElementByID. Remember, JavaScript is case sensitive.
What you need to do for run your code successfuly are simple 2 things:
Store all input (number) values in an array.
Use a reduce function to get easy the result for the multiply, sum and percentage.
For example:
function calculate_it() {
var inputs = document.querySelectorAll('input[type="number"]');
var multiply = 0;
var add = 0;
var percentage = 0;
// get the values of each input, map then and return
// a new array with the parsed numbers
var numbers = [].map.call(inputs, function (i) {
return parseFloat(i.value);
});
multiply = numbers.reduce(function (n1, n2) {
return n1 * n2;
});
add = numbers.reduce(function (n1, n2) {
return n1 + n2;
});
percentage = numbers.reduce(function (n1, n2) {
return (n1 / n2) * 100;
});
document.getElementById('ActionMulti').value = multiply.toFixed(2);
document.getElementById('ActionAdd').value = add.toFixed(2);
document.getElementById('ActionPercentage').value = percentage.toFixed(2);
document.getElementById('Sum').value = (multiply + add + percentage).toFixed(2);
}
The toFixed of Number class returns an string representation of the number with the maximum numner of decimals passed as argument. It method round (classic round) the number if is necessary.
Full example
function calculate_it() {
var inputs = document.querySelectorAll('input[type="number"]');
var multiply = 0;
var add = 0;
var percentage = 0;
// get the values of each input, map then and return
// a new array with the parsed numbers
var numbers = [].map.call(inputs, function (i) {
return parseFloat(i.value);
});
multiply = numbers.reduce(function (n1, n2) {
return n1 * n2;
});
add = numbers.reduce(function (n1, n2) {
return n1 + n2;
});
percentage = numbers.reduce(function (n1, n2) {
return (n1 * n2) / 100;
});
document.getElementById('ActionMulti').value = multiply.toFixed(2);
document.getElementById('ActionAdd').value = add.toFixed(2);
document.getElementById('ActionPercentage').value = percentage.toFixed(8);
document.getElementById('Sum').value = (multiply + add + percentage).toFixed(2);
}
input {
width: 100%;
}
<h3>A demonstration of calculators</h3>
<table id="t01">
<caption>Chek this out!</caption>
<tr>
<th>Date</th>
<th>Number 1</th>
<th>Number 2</th>
<th>Number 3</th>
<th>Number 4</th>
</tr>
<tr>
<td>
<input type="text" id="Date01" value="WED21DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb01" value=11.36 size="5" />
</td>
<td>
<input type="number" id="Numb02" value=12.36 size="5" />
</td>
<td>
<input type="number" id="Numb03" value=7.36 size="5" />
</td>
<td>
<input type="number" id="Numb04" value=4.36 size="5" />
</td>
</tr>
<tr>
<td>
<input type="text" id="Date02" value="WED22DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb05" value=8.36 size="5" />
</td>
<td>
<input type="number" id="Numb06" value=6.36 size="5" />
</td>
<td>
<input type="number" id="Numb07" value=10.36 size="5" />
</td>
<td>
<input type="number" id="Numb08" value=8.36 size="5" />
</td>
</tr>
<TR>
<td height="20" ColSpan="5"></td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Multiply:</td>
<td>
<input type="text" id="ActionMulti" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Add:</td>
<td>
<input type="text" id="ActionAdd" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Percentage:</td>
<td>
<input type="text" id="ActionPercentage" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>----------</td>
<td>--------</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Sum:</td>
<td>
<input type="text" id="Sum" value="" size="5" />
</td>
</TR>
</table>
<br>
<p>Click the button to calculate the data</p>
<button type="button" onclick="calculate_it()">calculate_it</button>

Change background Color for group radio inputs

Problem I have a form that the user fills out (basic things like your name, phone number, email, etc). It has a question that asks the user if you want your suggestion to remain anonymous and the user either selects yes or no.
The following image is what I am talking about:
If the user does not select either of the selections and submits the form, a alert box appears notifying the user to select one.
I am able to color a single radio selection red if the user has not selected either of them. I am able to color both radio selections red like the following:
And here is the function that checks whether or not either of those radio buttons have been selected:
myOption = -1;
for ( i=0; i < SubmitIdea.Anonymous.length; i++ ) {
if ( SubmitIdea.Anonymous[i].checked ) {
myOption = i;
}
}
if ( myOption == -1 ) {
alert( "Do you wish to remain anonymous?" );
SubmitIdea.Anonymous[0].focus();
SubmitIdea.Anonymous[0].style.backgroundColor = "red";
SubmitIdea.Anonymous[1].focus();
SubmitIdea.Anonymous[1].style.backgroundColor = "red";
return false;
}
However, I would like the rectangular background border surrounding both the Yes and No radio selection, not individually. This rectangular border will only occur if neither radio selection has been choosen when the user has submitted their results.
The following is the html:
<form name="SubmitIdea" method="POST" class="h">
<table Border="0" align="center">
<tr>
<td colspan="5"> </td>
</tr>
<cfoutput>
<tr>
<td class="m">Name: </font></td>
<td nowrap="nowrap" class="r">
<input type="text" name="Name" value="" class="a" maxlength="32">
</td>
<td width="50"> </td>
<td class="mm">Today's Date: </font></td>
<td class="mm">#TodaysDt#</td></tr>
</tr>
<tr>
<td class="mm">Department: </font></td>
<td nowrap="nowrap" class="r">
<input type="text" name="Department" value="" class="a" maxlength="32">
</td>
<td width="50"> </td>
<td class="mm">Supervisor Name: </font></td>
<td nowrap="nowrap" class="r">
<input type="text" name="Supervisor" value="" class="a" maxlength="32">
</tr>
<tr>
<td class="mm">Email: </font></td>
<td nowrap="nowrap" class="r">
<input type="text" name="NomEmail" value="" class="a" maxlength="32" size="25"> <br />
</td>
<td width="50"> </td>
<td class="mm">Phone: </font></td>
<td nowrap="nowrap" class="r">
<input type="text" name="Phone" value="" class="a" maxlength="32">
</tr>
</table>
<table border="0" width="500" align="center">
<tr>
<td class="c" align="center">
Your name will be shared and published along with your suggestion unless you want to remain anonymous. Do you wish to remain anonymous? <input type="radio" name="Anonymous" value="Yes"> <strong>Yes</strong> <input type="radio" value="No" name="Anonymous"> <strong>No</strong>
</td>
</tr>
</table>
</cfoutput>
<table border="0" align="center">
<tr>
<td colspan="5" class="r"><strong>Please provide a brief summary of your idea:</strong></td>
</tr>
</table>
<table border="0" align="center">
<tr>
<td colspan="5"></td>
</tr>
<tr>
<td colspan="5">
<textarea name="reason" id="textarea1" cols="6" maxlength="500" class="c"
style="background-color: transparent; color:##000000; font-size:14px;"
onFocus="clearTxt(this)" onkeydown="limitTxtArea(this); cntTxt(this, 500, 'cnt');" onkeyup="limitTxtArea(this); cntTxt(this, 500, 'cnt');"></textarea>
<span id="cnt" style="color:##FF0000">500</span> character(s) remaining.<br /></td>
</tr>
<tr>
<td colspan="5"> </td>
</tr>
</table>
<table border="0" align="center">
<tr>
<td colspan="5" class="r"><strong>I believe this suggestion will: (check all that apply)</strong></td>
</tr>
</table>
<table border="0" align="center">
<tr>
<td class="e"><input type="checkbox" name="Sugg1" value="Improve Productivity/Quality">Improve Productivity/Quality </font></td>
<td colspan="4"> </td>
<td class="e"><input type="checkbox" name="Sugg2" value="Improve Process">Improve Process </font></td>
</tr>
<tr>
<td class="e"><input type="checkbox" name="Sugg3" value="Increase Revenue">Increase Revenue </font></td>
<td colspan="4"> </td>
<td class="e"><input type="checkbox" name="Sugg4" value="Decrease Expenses/Costs">Decrease Expenses/Costs </font></td>
</tr>
<tr>
<td class="e"><input type="checkbox" name="Sugg5" value="Improve safety in the workplace">Improve safety in the workplace </font></td>
<td colspan="4"> </td>
<td class="e"><input type="checkbox" name="Sugg6" value="Improve Customer Service">Improve Customer Service </font></td>
</tr>
<tr>
<td class="e"><input type="checkbox" name="Sugg7" value="Enhance employee satisfaction / corporate culture">Enhance employee satisfaction/<br>corporate culture </font></td>
<td colspan="4"> </td>
<td class="e"><input type="checkbox" name="Sugg0" value="Other">Other <input type="text" name="OtherSuggest" value="" class="a" maxlength="32"></font></td>
</tr>
</table>
<table border="0" align="center">
<tr>
<td colspan="5" class="r"><strong>Possible challenges to implementation:</strong></td>
</tr>
</table>
<table border="0" align="center">
<tr>
<td colspan="5">
<textarea name="reasontwo" id="textarea2" cols="6" maxlength="500" class="c"
style="background-color: transparent; color:##000000; font-size:14px;"
onFocus="clearTxtTwo(this)" onkeydown="limitTxtAreaTwo(this); cntTxtTwo(this, 500, 'cnttwo');" onkeyup="limitTxtAreaTwo(this); cntTxtTwo(this, 500, 'cnttwo');"></textarea>
<span id="cnttwo" style="color:##FF0000">500</span> character(s) remaining.<br /></td>
</tr>
<tr>
<td colspan="5"> </td>
</tr>
</table>
<table border="0" align="center">
<tr>
<td colspan="5" class="r"><strong>What metrics could be used to track results?</strong></td>
</tr>
</table>
<table border="0" align="center">
<tr>
<td colspan="5">
<textarea name="reasonthree" id="textarea3" cols="6" maxlength="500" class="c"
style="background-color: transparent; color:##000000; font-size:14px;"
onFocus="clearTxtThree(this)" onkeydown="limitTxtAreaThree(this); cntTxtThree(this, 500, 'cntthree');" onkeyup="limitTxtAreaThree(this); cntTxtThree(this, 500, 'cntthree');"></textarea>
<span id="cntthree" style="color:##FF0000">500</span> character(s) remaining.<br /><br /></td>
</tr>
</table>
<br />
<table align="center">
<TR>
<TD align="center"><input type="button" value=" Submit " onClick="SubmitMe()" name="SubmitIdeaBtn" style="font-size:14px; font-family:Arial, Helvetica, sans-serif">
</td>
</tr>
</table>
</form>
Thank You
UPDATE
The following is what I did:
document.addEventListener("DOMContentLoaded", function(event) {
document.addEventListener("click", function(clickEvent) {
if (clickEvent.target.id == 'check') {
var anonymousInputs = document.getElementsByName('Anonymous');
var anonymousContainer = document.getElementById('anonymousContainer');
var anonymousSelected = Array.prototype.find.call(anonymousInputs,function(radioInput) {return radioInput.checked;});
if (anonymousSelected) {
anonymousContainer.className = '';
}
else {
if (anonymousContainer) {
alert( "Do you wish to remain anonymous?" );
anonymousContainer.className += 'borderedContainer';
}
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table border="0" width="500" align="center">
<tr>
<td class="c" align="center">
<div>
Your name will be shared and published along with your suggestion unless you want to remain anonymous. Do you wish to remain anonymous? <span id="anonymousContainer"><input type="radio" name="Anonymous" value="Yes"> <strong>Yes</strong>
<input type="radio" value="No" name="Anonymous">
<strong>No</strong>
</span>
</div>
</td>
</tr>
</table>
<table align="center">
<TR>
<TD align="center"><input id="check" type="button" value=" Submit " onClick="SubmitMe()" name="SubmitIdeaBtn" style="font-size:14px; font-family:Arial, Helvetica, sans-serif">
</td>
</tr>
</table>
So I am not sure what I am doing wrong.
You can put the radio buttons in a container (e.g. a span) and then set the border on the container. See the example below, after clicking the button labeled check.
The snippet uses the hex value for red but feel free to adjust to a different value. Using 'red' as the value may produce varying results across browsers/Operating systems. For more information, refer to the MDN color page.
The snippet also uses Array.find() to determine if any of the radio inputs are checked.
Note:
I originally utilized document.addEventListener() for event delegation and to wait until the DOM was loaded but the OP is using IE 8 or earlier and had issues with that, so I removed that code.
function checkAnonymousSelected(clickEvent) {
var anonymousInputs = document.getElementsByName('Anonymous');
var anonymousContainer = document.getElementById('anonymousContainer');
var anonymousSelected = Array.prototype.find.call(anonymousInputs, function(radioInput) {
return radioInput.checked;
});
if (anonymousSelected) {
anonymousContainer.className = '';
} else {
if (anonymousContainer) {
anonymousContainer.className += 'borderedContainer';
}
}
}
//support IE 8- for OP so do this instead of using document.attachEventListener
//to wait until the DOM is ready and attach event listeners to the buttons...
document.getElementById('check').onclick = checkAnonymousSelected;
document.getElementById('anonymousYes').onclick = checkAnonymousSelected;
document.getElementById('anonymousNo').onclick = checkAnonymousSelected;
.borderedContainer {
border: 3px solid #ff0000;
}
<div>
Your name will be shared and published along with your suggestion unless you want to remain anonymous. Do you wish to remain anonymous? <span id="anonymousContainer"><input type="radio" name="Anonymous" value="Yes" id="anonymousYes" > <strong>Yes</strong>
<input type="radio" value="No" name="Anonymous" id="anonymousNo" >
<strong>No</strong>
</span>
</div>
<button id="check">check</button>

How do I change a calculation based on a drop down box?

Disclaimer for possible question ignorance - I am super super green at coding Javascript and I'm looking for some friendly advice.
I am looking to code a very basic calculator for a website. This calculator works out a very simple calculation for heat output requirements for a room based on size. But I want the calculation to alter slightly based on a user selected drop down option, namely if the user wants to input in meters or feet.
Code is (currently) as follows:
function Calculate() {
var a = document.getElementById("height").value;
var b = document.getElementById("width").value;
var c = document.getElementById("depth").value;
var d = +a * +b * +c / 14;
var x = d.toFixed(2);
document.getElementById("result").innerHTML = x;
}
<form style="width:100px;" name="myForm">
<td>
<td>Units:</td>
<td>
<Select name="units">
<option>Metres</option>
<option>Feet</option>
</select>
</td>
</tr>
</form>
<form>
<table>
<tr>
<td style="padding-right:10px;">Height:</td>
<td>
<input style="width:100px;" type="text" name="Height" id="height">
</td>
</tr>
<tr>
<td style="padding-right:10px;">Width:</td>
<td>
<input style="width:100px;" type="text" name="Width" id="width">
</td>
</tr>
<tr>
<td style="padding-right:10px;">Depth:</td>
<td>
<input style="width:100px;" type="text" name="Depth" id="depth">
</td>
</tr>
<br>
<tr>
<td style="padding-right:10px;">
<input type="button" onclick="Calculate()" value="Calculate" />
</td>
</tr>
<tr>
<td style="padding-right:10px;">Heat output required in kW:</td>
<td>
<p id="result"></p>
</td>
</tr>
</table>
</form>
I'm basically looking for the drop down box to change the calculation in 'var d' from the stated calculation to
((+a * +b * +c) *0.03) /14
It's as simple as that. I've read various threads but they don't all seem to quite explain what I'm after.
Any help here would be greatly appreciated.
I would give your select an id then query your select and get the selected option's text. If it's 'Metres' do it one way otherwise do it the other way, like so:
function Calculate() {
var s = document.getElementById("units");
var measure = s.options[s.selectedIndex].text;
var a = document.getElementById("height").value;
var b = document.getElementById("width").value;
var c = document.getElementById("depth").value;
var d;
if(measure=="Metres")
d = +a * +b * +c / 14;
else
d = ((+a * +b * +c) *0.03) /14;
var x = d.toFixed(2);
document.getElementById("result").innerHTML = x;
}
<form style="width:100px;" name="myForm">
<td>
<td>Units:</td>
<td>
<Select name="units" id="units">
<option>Metres</option>
<option>Feet</option>
</select>
</td>
</tr>
</form>
<form>
<table>
<tr>
<td style="padding-right:10px;">Height:</td>
<td>
<input style="width:100px;" type="text" name="Height" id="height">
</td>
</tr>
<tr>
<td style="padding-right:10px;">Width:</td>
<td>
<input style="width:100px;" type="text" name="Width" id="width">
</td>
</tr>
<tr>
<td style="padding-right:10px;">Depth:</td>
<td>
<input style="width:100px;" type="text" name="Depth" id="depth">
</td>
</tr>
<br>
<tr>
<td style="padding-right:10px;">
<input type="button" onclick="Calculate()" value="Calculate" />
</td>
</tr>
<tr>
<td style="padding-right:10px;">Heat output required in kW:</td>
<td>
<p id="result"></p>
</td>
</tr>
</table>
</form>

Javascript math show decimal places

I almost have this working however the script is rounding my numbers while I wish to keep both decimals places for a full price instead of being automatically rounded up. My sandbox for this script is here:
http://www.zacharydesigns.com/sandbox/calculatorJS2.html
and here is the code:
<script type="text/javascript">
function update1() {
var a = +document.forms['calc'].elements['productOne'].value,
b = +document.forms['calc'].elements['productTwo'].value,
c = +document.forms['calc'].elements['productThree'].value,
productTotal = Math.floor(a/(a+b+c)*399.99);
document.forms['calc'].elements['productTotal1'].value = productTotal;
return false;
}
function update2() {
var a = +document.forms['calc'].elements['productOne'].value,
b = +document.forms['calc'].elements['productTwo'].value,
c = +document.forms['calc'].elements['productThree'].value,
productTotal = Math.floor(b/(a+b+c)*399.99);
document.forms['calc'].elements['productTotal2'].value = productTotal;
return false;
}
function update3() {
var a = +document.forms['calc'].elements['productOne'].value,
b = +document.forms['calc'].elements['productTwo'].value,
c = +document.forms['calc'].elements['productThree'].value,
productTotal = Math.floor(c/(a+b+c)*399.99);
document.forms['calc'].elements['productTotal3'].value = productTotal;
return false;
}
</script>
<form name="calc" action="#">
<table align="center"
border="1"><tr><td align="right">Boots: </td>
<td align="left"><input type="text" name="productOne" size="5" />
</td>
<td colspan="2" align="center">
<input type="button" value="Calculate"
onclick="update1();" /> </td>
<td align="right">Product Total:</td><td align="left">
<input type="text" name="productTotal1" size="6"
readonly="readonly" /></td>
</tr>
<tr>
<td align="right">Bindings: </td>
<td align="left"><input type="text" name="productTwo" size="5" />
</td>
<td colspan="2" align="center">
<input type="button" value="Calculate"
onclick="update2();" /> </td>
<td align="right">Product Total:</td><td align="left">
<input type="text" name="productTotal2" size="6"
readonly="readonly" /></td>
</tr><tr>
<td align="right">Boards: </td>
<td align="left"><input type="text" name="productThree" size="5" />
</td>
<td colspan="2" align="center">
<input type="button" value="Calculate"
onclick="update3();" /> </td>
<td align="right">Product Total:</td><td align="left">
<input type="text" name="productTotal3" size="6"
readonly="readonly" /></td>
</tr><tr></tr>
</tr>
</table></form>
Can someone please tell me how I can have math operated on the full number without rounding it?
I think that the issue is that you are using the floor operator. The floor operator always rounds down to the nearest integer so:
floor(3.5) == 3
floor(5.9999999999999999999999999999) = 5
floor(5) = 5
And I think you get the drift. That you want to do is format the decimal places and the toFixed() function is for that.
So basically, change these lines:
productTotal = Math.floor(c/(a+b+c)*399.99);
To:
productTotal = (c/(a+b+c)*399.99).toFixed(2);
And I think that will be what you want.

Categories