How to prevent HTML form output from being styled? - javascript

I'm building a form that takes input including a few texareas and outputs what was input into those fields on the same page below the form. It works great, except when I paste a multi-line code snippet in any of the textareas, the output does not look like what I pasted originally.
How can I prevent code in my #results div from being styled?
Here is a screenshot showing the output of texarea elements being mis-aligned, and mis-formatted. Everything from the "FILE" to "TAGS" heading displays and is formatted correctly.
I had trouble finding the right long-tail term to Google on for this. Perhaps someone can tell me what the correct term is for this kind of
output produced from self-submitting form?
My Code:
submit.onclick = function() {
// build html output
document.querySelectorAll('input, textarea').value = "";
var out = "";
//var form = document.querySelector('form');
var outPartsArr = [];
/* GATHER FORM VALUES */
var filename = document.querySelector('#filename').value;
var dateCreated = document.querySelector('#date-created').value;
var dateModified = document.querySelector('#date-modified').value;
var postURL = document.querySelector('#post-url').value;
var postTitle = document.querySelector('#post-title').value;
var postTags = document.querySelector('#post-tags').value;
var postContent = document.querySelector('#post-content').value;
/* GET TIME */
// from: https://www.codexworld.com/how-to/get-current-date-time-using-javascript/
var today = new Date();
var yy = today.getFullYear().toString().substr(-2);
var mm = today.getMonth()+1;
var dd = today.getDate() < 10 ? "0" + today.getDate() : today.getDate() ;
var date = mm + "/" + dd + "/" + yy;
var hh = today.getHours() > 12 ? today.getHours() - 12 : today.getHours();
var mm = today.getMinutes();
var time = hh + ":" + mm;
/* BUILD OUTPUT */
var filenameOut = "<span class='line-title'>FILE: </span>" + filename + "<br>";
var dateCreatedOut = "<span class='line-title'>DATE CREATED: </span>" + dateCreated + "<br>";
var dateModifiedOut = "<span class='line-title'>DATE MODIFIED: </span>" + dateModified + "<br>";
var postURLOut = "<span class='line-title'>URL: </span>" + postURL + "<br>";
var postTitleOut = "<span class='line-title'>TITLE: </span>" + postTitle + "<br>";
var postTagsOut = "<span class='line-title'>TAGS: </span>" + postTags + "<br>";
var postContentOut = "<span class='line-title'>CONTENT: </span>" + "<pre>" + postContent + "</pre><br>";
// Add each line item html snippet to array
outPartsArr.push(filenameOut, dateCreatedOut, dateModifiedOut, postURLOut, postTitleOut, postTagsOut, postContentOut);
console.log("%c postContent ","background:orange");
console.log(postContent);
out += "<ul class='row-lines'>"
// loop through out parts array and wrap each in <li> tags
// while building the out string
outPartsArr.forEach(function(part, i) {
out += "\t<li>" + part + "</li>";
});
out += "</ul>";
console.log("%c out ","background:orange");
console.log(out);
// display in results div
document.querySelector('#results').innerHTML = out;
// #GOTCHA --> Without this return statement output appears for a milisecond
// then the form refreshes.
return false;
};
* {
box-sizing: border-box;
}
body {
width: 100%;
}
#wrapper {
max-width: 1024px;
width: 80%;
border: solid gray 1px;
margin: 2em auto;
padding: 1.2em
}
form {
border: solid red 2px;
background: aliceblue;
margin-bottom: 1.5em;
padding: .6em;
}
form label {
margin-right: 0;
padding-right: 0;
width: 200px;
float: left;
font-family: Arial, Tahoma, sans-serif;
font-weight: bold;
}
form input {
padding: .4em .6em;
margin-bottom: .4em;
width: 80%;
}
form input[type="submit"] {
background: green;
color: white;
margin-top: 1em;
width: 6em;
border-radius: .3em;
margin-left: 0;
}
textarea {
width: 80%;
height: 10em;
/*resize: both;*/
border-radius: 5px;
border: 1px solid #ccc;
box-shadow: 1px 1px 1px #999;
}
/* OUTPUT */
#results {
padding: 2em .6em;
background: #ffffb3;
border: solid brown 1px;
}
#results h3 {
font-family: Arial, Tahoma, sans-serif;
color: brown;
}
.line-title {
font-weight: bold;
float: left;
width: 10em;
color: brown;
font-family: Arial, Tahoma, sans-serif;
line-height: 1.2em;
}
.row-lines li {
line-height: 2em;
list-style: none;
}
<div id="wrapper">
<header class="content">
<h1>Eric Hepperle's Stack Overflow Post Builder (2018)</h1>
<p>Some header tag line or other introductory text.</p>
</header>
<main>
<form id="stack-post-builder" method="GET" action="#">
<label for="filename">FILE:</label>
<input type="text" id="filename" name="filename" value="" ><br>
<label for="date-created">DATE CREATED:</label>
<input type="text" id="date-created" name="date-created" value=""><br>
<label for="date-modified">DATE MODIFIED:</label>
<input type="text" id="date-modified" name="date-modified" value=""><br>
<label for="post-url">URL:</label>
<input type="text" id="post-url" name="post-url" value="" ><br>
<label for="post-title">TITLE:</label>
<input type="text" id="post-title" name="post-title" value="" ><br>
<label for="post-tags">TAGS:</label>
<textarea id="post-tags" name="post-tags" placeholder="Enter post tags"></textarea><br>
<label for="post-content">CONTENT:</label>
<textarea id="post-content" name="post-content" placeholder="Enter post tags"></textarea><br>
<!-- <input type="submit" id="stack-post-builder-submit" name="stack-post-builder-submit" value="Submit"> -->
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<section id="results">Results will show up here.</section>
</main>
</div><!-- END wrapper div -->

Related

Jquery Fade Cycle through paragraphs and display one item at a time

I cannot get it to just display one at a time. It has to do a full cycle before it displays just one paragraph. Pulling my hair out.
$(function(){
setInterval(function(){$('.forumFeed > :first-child').fadeOut(3000).next('p').delay(3000).fadeIn(1000).end().appendTo('.forumFeed');}, 5000);
});
https://codepen.io/capseaslug/pen/yqyBXB
Hide all but the first paragraph tag by default. Inside the setInterval hide the one that is showing and display the next one (controlled by an index variable).
To make the items fade in/out nicely you can fade in the next element after the visible one is finished hiding.
Added some variables at the top to play with the aesthetics / number of items looped through.
SO didn't have moment.js so I hard coded some string. Codepen for a working version.
var numberOfItems = 10;
var flipSpeed = 2000;
var fadeOutSpeed = 500;
var fadeInSpeed = 200;
(function(c){
var uniquename = 'rssfeed' // id of target div
var query = 'select * from rss(0,' + numberOfItems + ') where url = "https://forums.mankindreborn.com/f/-/index.rss"'; // RSS Target, 0,5 signifies number of entries to show
var numretries = 1; // increase this number (number of retries) if you're still having problems
//////// No Need To Edit Beyond Here Unless You Want To /////////
var counter = typeof c === 'number'? c : numretries;
var thisf = arguments.callee;
var head = document.getElementsByTagName('head')[0];
var s = document.createElement('script');
window["callback_" + uniquename + (--counter)] = function(r){
head.removeChild(s);
if(r && r.query && r.query.count === 0 && counter > 0){
return thisf(counter);
}
//r now contains the result of the YQL Query as a JSON
var feedmarkup = '';
var feed = r.query.results.item // get feed as array of entries
for (var i=0; i<feed.length; i++) {
feedmarkup += '<p><span class="firstrowwrap"><a href="' + feed[i].link + '">';
feedmarkup += feed[i].title + '</a> <span class="comments"> Replies: ';
feedmarkup += feed[i].comments + ' </span></span><span class="secondRow"> <i class="fas fa-feather-alt"></i> ' ;
feedmarkup += feed[i].creator + ' <span class="posttime"> Last Post: ';
//pubishdate since
publishDate = feed[i].pubDate;
var inDate = publishDate;
var publisheddate = new Date(inDate);
feedmarkup += 'moment.js is missing ' + '</span></span></p>';
//endpublishdate since
}
document.getElementById(uniquename).innerHTML = feedmarkup;
};
var baseurl = "https://query.yahooapis.com/v1/public/yql?q=";
s.src = baseurl + encodeURIComponent(query) + "&format=json&callback=callback_" + uniquename + counter;
head.append(s);
})();
$(function(){
var index = 0;
setInterval(function() {
$('#rssfeed>p:visible').fadeOut(fadeOutSpeed, ()=> {
$('#rssfeed>p').eq(index).fadeIn(fadeInSpeed);
});
index++;
if(index === $('#rssfeed>p').length){
index = 0;
}
}, flipSpeed);
});
#main-container {
padding:4em;
background: #333;
font-family: 'exo'
}
#rssfeed p:not(:first-child) {
display: none;
}
a{
font-weight:
500;
color: #68ddda;
}
a:hover{
color: #4ca7a4;
}
.firstrowwrap{
display: flex;
justify-content: space-between;
}
.secondRow{
display: block;
padding-top: 4px;
margin-bottom: -5px;
}
#rssfeed p{
background-color: #212121;
padding: 10px;
width: 400px;
margin-bottom: 2px;
color: #464646;
}
.comments{
height: 18px;
position: relative;
z-index: 1;
padding-left: 8px;
margin-left: 4px;
font-size: 12px;
}
.comments:after{
content: "";
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 0px;
background-color: #969696;
border-radius: 2px;
z-index: -1;
margin-left: 4px;
}
.posttime{
float: right;
font-size: 13px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid" id="main-container">
<div class="row">
<div class="col-md-12">
<div class="forumFeed" id="rssfeed"></div>
</div>
</div>
</div>

Reflow/repaint issues? Optimize app that is way too slow

Alright so I have run into what I believe is an optimization issue. I have written a short app that grabs data from two fields, rips them apart character by character and matches them to each other, highlighting discrepancies. The issue seems to be that because the function loops through and not only prints each character one at a time, but changes color in a new span one at a time, there is a severe amount of bottlenecking for large data entries. One sentence of even five work just fine, but when you get up to a full page of text, things bog down and in some cases crash. I have tried to look up some fixes for repaints/reflows, but I haven't run into this issue before and don't know much about it. ANy tips welcome.
Code is here:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Data Comparison</title>
</head>
<body>
<p><strong>Insert text into fields one and two and press 'Compare'. Matching data is green non-matching is red. </strong></p>
<div class="userField">
<h1>Input Field 1</h1>
<textarea id="textAreaOne" rows="30" cols="65"></textarea>
</div>
<div class="userField">
<h1>Input Field 2</h1>
<textarea id="textAreaTwo" rows="30" cols="65"></textarea>
</div>
<div id="submission">
<button onclick="compare(textAreaOne);">Compare</button>
</div>
<div id="divOne">
<h1 id="titleOne">Output Field 1</h1>
<p id="outputOne"></p>
</div>
<div id ="divTwo">
<h1 id="titleTwo">Output Field 2</h1>
<p id="outputTwo"></p>
</div>
</body>
</html>
CSS:
body {
width: 100%;
margin: 0;
padding: 0;
font-family: Verdana, Geneva, sans-serif;
font-size: 15px;
}
.userField {
display: inline-block;
width: 44%;
margin: 15px;
padding: 15px;
background-color: lightgrey;
border-radius: 13px;
box-shadow: 3px 3px 3px slategrey;
}
#submission {
text-align: center;
}
#divOne {
display: inline-block;
margin: 15px;
padding: 15px;
width: 44%;
word-wrap: break-word;
background-color: lightgrey;
}
#divTwo {
display: inline-block;
background-color: lightgrey;
width: 44%;
word-wrap: break-word;
margin: 15px;
padding: 15px;
}
#titleOne {
background-color: white;
width: 240px;
border-radius: 30px;
padding: 6px;
}
#titleTwo {
background-color: white;
width: 240px;
border-radius: 30px;
padding: 6px;
}
JS:
const fieldOne = document.querySelector("#textAreaOne");
const fieldTwo = document.querySelector("#textAreaTwo");
function compare(){
document.querySelector("#outputOne").innerHTML = "";
document.querySelector("#outputTwo").innerHTML = "";
document.querySelector("#divOne").style.visibility = "hidden";
document.querySelector("#divTwo").style.display = "hidden";
let dataOne = [];
let arrOne = fieldOne.value;
let temp = arrOne.split("");
dataOne.push(temp);
let dataTwo = [];
let arrTwo = fieldTwo.value;
let tempTwo = arrTwo.split("");
dataTwo.push(tempTwo);
if (fieldOne.value.length <= fieldTwo.value.length){
for (var i = 0; i<fieldOne.value.length; i++){
if (dataOne[0][i] === dataTwo[0][i]){
document.querySelector("#outputOne").innerHTML += "<span style='color:green'>" + dataOne[0][i] + "</span>";
document.querySelector("#outputTwo").innerHTML += "<span style='color:green'>" + dataTwo[0][i] + "</span>";
} else {
document.querySelector("#outputOne").innerHTML += "<span style='color:red'>" + dataOne[0][i] + "</span>";
document.querySelector("#outputTwo").innerHTML += "<span style='color:red'>" + dataTwo[0][i] + "</span>";
}
}
if (fieldOne.value.length < fieldTwo.value.length){document.querySelector("#outputTwo").innerHTML += "<span>...</span>";}
}
else {
for (var i = 0; i<fieldTwo.value.length; i++){
if (dataOne[0][i] === dataTwo[0][i]){
document.querySelector("#outputOne").innerHTML += "<span style='color:green'>" + dataOne[0][i] + "</span>";
document.querySelector("#outputTwo").innerHTML += "<span style='color:green'>" + dataTwo[0][i] + "</span>";
} else {
document.querySelector("#outputOne").innerHTML += "<span style='color:red'>" + dataOne[0][i] + "</span>";
document.querySelector("#outputTwo").innerHTML += "<span style='color:red'>" + dataTwo[0][i] + "</span>";
}
}
if (fieldTwo.value.length < fieldOne.value.length){ document.querySelector("#outputOne").innerHTML += "<span>...</span>";}
}
document.querySelector("#divOne").style.visibility = "visible";
document.querySelector("#divTwo").style.visibility = "visible";
}
https://codepen.io/Axfinger/pen/QxvbqM?editors=0010
Thanks
The main reason your code is slow it's because you keep modify innerHtml for every letter.
This approach is way faster even with several paragraph:
[...]
let outOne = '';
let outTwo = '';
if (fieldOne.value.length <= fieldTwo.value.length){
for (var i = 0; i<fieldOne.value.length; i++){
if (dataOne[0][i] === dataTwo[0][i]){
outOne += dataOne[0][i];
outTwo += dataTwo[0][i];
} else {
outOne += "<span style='color:red'>" + dataOne[0][i] + "</span>";
outTwo += "<span style='color:red'>" + dataTwo[0][i] + "</span>";
}
}
if (fieldOne.value.length < fieldTwo.value.length){outTwo += "...";}
}
[...]
outputOne.innerHTML = outOne;
outputTwo.innerHTML = outTwo;
Note that I omitted parts of the code for clearness.
That said if you still need more speed:
Lookup for fitting as much data as possible into the red spans. That is the whole consecutive subsequence of different letters.
Execute the function in a webworker (Will take similar time but at least won't freeze the browser).

Resizing DIV depending on amount of characters in text field

I have made a text box, which i enter text into and it gets printed out in a div below as it is typed. Currently, the DIV can fit 24 characters into it and then i have the text to wrap. What i'm trying to do is to get the DIV to double in height for every 24 characters that are entered.
I want to do this using only Javascript and no jQuery
<div class="one">Input Some Text
<form>
<input type="text" id="pointlessInput"/>
<script>
var stringToBePrinted = document.getElementById("pointlessInput");
var len = stringToBePrinted.length;
stringToBePrinted.onkeyup = function(){
var len = stringToBePrinted.length;
document.getElementById("printbox").innerHTML = stringToBePrinted.value;
if(document.getElementById("pointlessInput").innerHTML.value.length == 24){
document.getElementById("printbox").style.height = "4em";
}
}
</script>
</form>
<div class="printbox" id="printbox"></div>
</div>
stylesheet
.printbox {
border-width:thick 10px;
border-style: solid;
background-color:#fff;
line-height: 2;
color:#6E6A6B;
font-size: 14pt;
text-align:center;
border: 3px solid #969293;
width:50%;
height:2em;
margin: auto;
word-wrap: break-word;
}
var stringToBePrinted = document.getElementById("pointlessInput");
stringToBePrinted.onkeyup = function() {
document.getElementById("printbox").innerHTML = stringToBePrinted.value;
var multiple = Math.ceil(parseInt(document.getElementById("pointlessInput").value.length) / 24);
document.getElementById("printbox").style.height = (multiple * 2) + "em";
}
Remove the if condition and the height from the css, it works just fine.
Check the below working example.
var stringToBePrinted = document.getElementById("pointlessInput");
var len = stringToBePrinted.length;
stringToBePrinted.onkeyup = function(){
var len = stringToBePrinted.length;
document.getElementById("printbox").innerHTML = stringToBePrinted.value;
}
.printbox {
border-width:thick 10px;
border-style: solid;
background-color:#fff;
line-height: 2;
color:#6E6A6B;
font-size: 14pt;
text-align:center;
border: 3px solid #969293;
width:50%;
margin: auto;
word-wrap: break-word;
}
<div class="one">Input Some Text
<form>
<input type="text" id="pointlessInput"/>
<script>
</script>
</form>
<div class="printbox" id="printbox"></div>
</div>

Textarea won't display values after hitting Reset

The reset button only appears once a conversion from Fahrenheit to Celsius is successfully done. It works fine. However, after hitting Reset, I cannot see values in the textarea when perform more conversions. I think the problem is most likely caused the two arrays in my codes. What do you think?
I have recreated the problem here: http://jsfiddle.net/wnna3646/
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Temperature Conversion</title>
<style type="text/css">
body { font: 1em calibri, arial; }
button {
background-color: transparent;
margin: 5px;
width: 300px;
}
h1, h2, h3, h4 { text-align: center; }
table {
border: 8px double;
margin-left: auto;
margin-right: auto;
padding: 2px;
height: 500px;
width: 30%;
}
td { border: 1px solid; }
td#topcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#midcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#bottomcell { text-align: center; }
textarea {
width: 250px;
height: 250px;
}
p {
word-spacing: 25px;
}
#Fahr {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#Cels {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#ftemp, #ctemp {
display: inline;
float: middle;
}
</style>
</head>
<body>
<main role="main">
<form id="myForm" onsubmit="return this.ftemp.value!=''">
<table>
<tr>
<td id="topcell">
<label for="Fahrenheit" id="Fahr">Fahrenheit:</label><input id="ftemp" onkeypress="return fNumericCharactersOnly(event)" onkeyup="this.form.Convertbtn.disabled = this.value==''; this.form.Avgbtn.disabled = this.value==''; if(!validnum(this.value)) this.value=''">
<br /><br />
<label for="Celsius" id="Cels" >Celsius:</label><input id="ctemp" readonly>
<br /><br /><br /><br /><br /><br />
<p>Fahrenheit Celsius</p>
</td>
</tr>
<tr>
<td id="midcell">
<br />
<textarea rows="5" id="txtArea" readonly></textarea>
</td>
</tr>
<tr>
<td id="bottomcell">
<input type="button" id="Convertbtn" value="Convert" accesskey="c" onclick="convertTemp(); counter++" disabled="disabled"/>
<input type="button" id="Avgbtn" value="Average" accesskey="a" onclick="averageTemp(); AddResetbutton()" disabled="disabled"/>
<div id="ButtonSpot"></div>
</td>
</tr>
</table>
</form>
</main>
<script type="text/javascript">
var flist = [];
var clist = [];
var counter = 0;
function validnum(F) {
if(F < -9999 || F > 9999)
return false;
else
return true;
}
function fNumericCharactersOnly(evt){
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
return (charCode >= 48 && charCode <= 57); // 48 to 57 ==> 0 to 9
}
function convertTemp() {
var c = document.getElementById('ctemp'),
f = document.getElementById('ftemp');
c.value = parseFloat(Math.round((f.value - 32) * 5 / 9)).toFixed(2);
tf = f.value, tc = c.value;
flist.push(tf); clist.push(tc);
var str = "";
str += '\t' + tf + '\t' + '&nbsp' + '&nbsp' + tc + "\n";
document.getElementById("txtArea").innerHTML = str;
}
function averageTemp() {
var content="";
var sumF = 0;
var sumC = 0;
for (var i = 0; i < flist.length; i++) {
content += '\t' + flist[i] + '\t' + '&nbsp' + '&nbsp' + clist[i] + "\n";
sumF += parseInt(flist[i], 10);
sumC += parseInt(clist[i], 10);
}
bars = '===============================';
var avgF = parseFloat(sumF / flist.length).toFixed(2);
var avgC = parseFloat(sumC / clist.length).toFixed(2);
document.getElementById("txtArea").innerHTML = content + bars + "\n" + '\t' + avgF + '\t' + '&nbsp' + '&nbsp' + avgC;
flist = [];
clist = [];
document.getElementById("Avgbtn").disabled=true;
}
function AddResetbutton() {
document.getElementById('ButtonSpot').innerHTML = '<input type="button" onClick="removeButton();" value="Reset" />';
document.getElementById("Convertbtn").disabled=true;
}
function removeButton() {
document.getElementById("myForm").reset();
document.getElementById('ButtonSpot').innerHTML = '';
document.getElementById("txtArea").value = "";
document.getElementById("Convertbtn").disabled=true;
document.getElementById("Avgbtn").disabled=true;
}
</script>
</body>
</html>
Also, I have attempted to make the script automatically display all values after the 10th one is entered, but can't seem to make it work. Any suggestions?
Hey Your code is fixed.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Temperature Conversion</title>
<style type="text/css">
body { font: 1em calibri, arial; }
button {
background-color: transparent;
margin: 5px;
width: 300px;
}
h1, h2, h3, h4 { text-align: center; }
table {
border: 8px double;
margin-left: auto;
margin-right: auto;
padding: 2px;
height: 500px;
width: 30%;
}
td { border: 1px solid; }
td#topcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#midcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#bottomcell { text-align: center; }
textarea {
width: 250px;
height: 250px;
}
p {
word-spacing: 25px;
}
#Fahr {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#Cels {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#ftemp, #ctemp {
display: inline;
float: middle;
}
</style>
</head>
<body>
<main role="main">
<form id="myForm" onsubmit="return this.ftemp.value!=''">
<table>
<tr>
<td id="topcell">
<label for="Fahrenheit" id="Fahr">Fahrenheit:</label><input id="ftemp" onkeypress="return fNumericCharactersOnly(event)" onkeyup="this.form.Convertbtn.disabled = this.value==''; this.form.Avgbtn.disabled = this.value==''; if(!validnum(this.value)) this.value=''">
<br /><br />
<label for="Celsius" id="Cels" >Celsius:</label><input id="ctemp" readonly>
<br /><br /><br /><br /><br /><br />
<p>Fahrenheit Celsius</p>
</td>
</tr>
<tr>
<td id="midcell">
<br />
<textarea rows="5" id="txtArea" name="textarea-name" readonly></textarea>
</td>
</tr>
<tr>
<td id="bottomcell">
<input type="button" id="Convertbtn" value="Convert" accesskey="c" onclick="convertTemp(); counter++" disabled="disabled"/>
<input type="button" id="Avgbtn" value="Average" accesskey="a" onclick="averageTemp(); AddResetbutton()" disabled="disabled"/>
<div id="ButtonSpot"></div>
</td>
</tr>
</table>
</form>
</main>
<script type="text/javascript">
var flist = [];
var clist = [];
var counter = 0;
function validnum(F) {
if(F < -9999 || F > 9999)
return false;
else
return true;
}
function fNumericCharactersOnly(evt){
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
return (charCode >= 48 && charCode <= 57); // 48 to 57 ==> 0 to 9
}
function convertTemp() {
var c = document.getElementById('ctemp'),
f = document.getElementById('ftemp');
c.value = parseFloat(Math.round((f.value - 32) * 5 / 9)).toFixed(2);
tf = f.value, tc = c.value;
flist.push(tf); clist.push(tc);
var str = "";
str += '\t' + tf + '\t' + '&nbsp' + '&nbsp' + tc + "\n";
document.getElementById("txtArea").innerHTML = str;
}
function averageTemp() {
var content="";
var sumF = 0;
var sumC = 0;
for (var i = 0; i < flist.length; i++) {
content += '\t' + flist[i] + '\t' + '&nbsp' + '&nbsp' + clist[i] + "\n";
sumF += parseInt(flist[i], 10);
sumC += parseInt(clist[i], 10);
}
bars = '===============================';
var avgF = parseFloat(sumF / flist.length).toFixed(2);
var avgC = parseFloat(sumC / clist.length).toFixed(2);
document.getElementById("txtArea").innerHTML = content + bars + "\n" + '\t' + avgF + '\t' + '&nbsp' + '&nbsp' + avgC;
flist = [];
clist = [];
document.getElementById("Avgbtn").disabled=true;
}
function AddResetbutton() {
document.getElementById('ButtonSpot').innerHTML = '<input type="button" onClick="removeButton();" value="Reset" />';
document.getElementById("Convertbtn").disabled=true;
}
function removeButton() {
document.getElementById("myForm").reset();
document.getElementById('ButtonSpot').innerHTML = '';
document.getElementById("txtArea").innerHTML = '';
document.getElementById("Convertbtn").disabled=true;
document.getElementById("Avgbtn").disabled=true;
}
</script>
</body>
</html>

Javascript Loan Calculator with While loop

The program is supposed to determine how many months it will take to pay off the loan. Cannot seem to figure out how to fix my mathematical calculations. Not sure if it's the while loop that's wrong. Instead of determining the monthly payment based on user input, the input shows the total number of months (which i do not want. the program is supposed to do that). It is supposed to look like this: http://snag.gy/9vzGi.jpg Here is the code:
<html>
<head>
<title></title>
<script type="text/javascript">
function fixVal(value,numberOfCharacters,numberOfDecimals,padCharacter) {
var i, stringObject, stringLength, numberToPad;
value = value * Math.pow(10,numberOfDecimals);
value = Math.round(value);
stringObject = new String(value);
stringLength = stringObject.length;
while(stringLength < numberOfDecimals) {
stringObject = "0"+stringObject;
stringLength=stringLength+1;
}
if(numberOfDecimals>0) {
stringObject=stringObject.substring(0,stringLength-numberOfDecimals)+"."+
stringObject.substring(stringLength-numberOfDecimals,stringLength);
}
if (stringObject.length<numberOfCharacters && numberOfCharacters>0) {
numberToPad=numberOfCharacters-stringObject.length;
for (i=0; i<numberToPad; i=i+1) {
stringObject=padCharacter+stringObject;
}
}
return stringObject;
}
function buildTable() {
var amount=parseFloat(document.getElementById("loanAmt").value );
var numpay=parseInt(document.getElementById("monthlyPay").value );
var rate=parseFloat(document.getElementById("intRte").value );
rate = rate / 100;
var monthly = rate / 12;
var payment = ((amount * monthly) / (1-Math.pow((1 + monthly), - numpay)));
var total = payment * numpay;
var interest = total - amount;
var msg = "<table border='4' width='75%'>";
msg += "<tr>";
msg += "<td>Month</td>";
msg += "<td>Principal Paid</td>";
msg += "<td>Interest Paid</td>";
msg += "<td>Loan Balance</td>";
msg += "</tr>";
newPrincipal=amount;
var i = 1;
while (i <= numpay) {
newInterest=monthly*newPrincipal;
reduction=payment-newInterest;
newPrincipal=newPrincipal-reduction;
msg += "<tr><td align='left' bgcolor='pink'>"+i+"</td> \
<td align='left' bgcolor='pink'>"+fixVal(reduction,0,2,' ')+"</td> \
<td align='left' bgcolor='pink'>"+fixVal(newInterest,0,2,' ')+"</td> \
<td align='left' bgcolor='pink'>"+fixVal(newPrincipal,0,2,' ')+"</td></tr>";
i++;
}
msg += "</table>";
document.getElementById("results").innerHTML = msg;
}
</script>
<style type="text/css">
body {
background: black;
font-family: arial;
}
#contentwrap {
width: 700px;
margin: 40px auto 0px auto;
background: #FFFFCC;
text-align: center;
border: 6px red solid;
border-radius: 10px;
padding: 40px;
}
table {
border: 5px blue double;
background-color: #FFFFCC;
}
#header {
text-align: center;
font-size: 2.5em;
text-shadow: yellow 3px 3px;
margin-bottom: 18px;
color: red;
}
#button {
background: blue;
color: white;
cursor: pointer;
padding: 5px 0px 5px 0px;
border: 1px solid red;
border-radius: 25px;
width: 150px;
}
.contentTitles {
color: green;
font-weight: bold;
}
.style {
background: lightblue;
font-family: comic sans ms;
border: 6px blue double;
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<div id="contentwrap">
<div id="header">Javascript Loan Calculator</div>
<form>
<div class="contentTitles">Enter Loan Amount<br />
<input type="text" id="loanAmt" class="style"><p />
Interest Rate (%)<br />
<input type="text" id="intRte" class="style"><p />
Monthly Payment Amount<br />
<input type="text" id="monthlyPay" class="style"><p />
<div style="margin-top:20px;">
<input type="button" value="Process Data" id="button" onClick="buildTable()">
</div>
</form>
<center>
<div id="results" style="margin-top:20px;"></div>
</center>
</div> <!-- ends div#contentwrap -->
</body>
</html>
If you want the input to be the monthly payment, please don't call the respective variable numpay.
In your case, it seems more practical not to calculate the number of months beforehand. You can use the while loop to build the table and calculate the duration of the loan at the same time:
function buildTable() {
var amount = parseFloat(document.getElementById("loanAmt").value );
var monthly = parseInt(document.getElementById("monthlyPay").value );
var rate = parseFloat(document.getElementById("intRte").value );
rate = rate / 100 / 12;
var m = 0; // number of months
while (amount > 0) {
var interest = amount * rate;
var principal = monthly - interest;
if (principal > amount) {
principal = amount;
amount = 0.0;
} else {
amount -= principal;
}
// build table: m + 1, principal, interest, amount
m++;
}
// display table
}

Categories

Resources