I can't find a good calculator in JavaScript.
In a first time I was using the eval function on my datas to get my result but there were mistakes.
So I found this code:
function calculate(input){
var f = { add : '+'
, sub : '-'
, div : '/'
, mlt : '*'
, mod : '%'
, exp : '^' };
// Create array for Order of Operation and precedence
f.ooo = [[ [f.mlt] , [f.div] , [f.mod] , [f.exp] ],
[ [f.add] , [f.sub] ]];
input = input.replace(/[^0-9%^*\/()\-+.]/g,''); // clean up unnecessary characters
var output;
for(var i=0, n=f.ooo.length; i<n; i++ ){
// Regular Expression to look for operators between floating numbers or integers
var re = new RegExp('(\\d+\\.?\\d*)([\\'+f.ooo[i].join('\\')+'])(\\d+\\.?\\d*)');
re.lastIndex = 0; // be cautious and reset re start pos
// Loop while there is still calculation for level of precedence
while( re.test(input) ){
//document.write('<div>' + input + '</div>');
output = calc_internal(RegExp.$1,RegExp.$2,RegExp.$3);
if (isNaN(output) || !isFinite(output)) return output; // exit early if not a number
input = input.replace(re,output);
}
}
return output;
function calc_internal(a,op,b){
a=a*1; b=b*1;
switch(op){
case f.add: return a+b; break;
case f.sub: return a-b; break;
case f.div: return a/b; break;
case f.mlt: return a*b; break;
case f.mod: return a%b; break;
case f.exp: return Math.pow(a,b); break;
default: null;
}
}
}
http://jsfiddle.net/vol7ron/6cdfA/
But there are some problems using parenthesis, for example: (10+1)*5 = 11
So I'm trying to find a good calculator in JavaScript to calculate string expressions.
Thanks for your help.
You can use the math.js library, which comes with a powerful expression parser:
http://mathjs.org
I don't have javascript code for it, but general solution how to evaluate complex expresion in string is to convert it using Shunting-yard algorithm into RPN and then use Reverse Polish notation algorithm to get result.
This is a solution i recently come up with as an exercise for using clusure in Javascript.
var PocketCalculator = function() {
var allowedOperators = ["+", "-", "*", "/", "="],
operations = {
"+": function(a, b) {
return a + b;
},
"-": function(a, b) {
return a - b;
},
"*": function(a, b) {
return a * b;
},
"/": function(a, b) {
return a / b;
}
},
cache = 0,
makeOperation = function(b, f) {
return function() {
return cache = f(cache, b);
};
},
prevOperation = operations["+"],
operation = makeOperation(0, prevOperation);
return {
clear: function() {
cache = 0;
prevOperation = operations["+"]
operation = makeOperation(0, prevOperation);
},
push: function(operator, b) {
if (allowedOperators.indexOf(operator) < 0)
return;
if (operator !== "=") {
prevOperation = operations[operator];
operation = makeOperation(b, prevOperation);
} else if (b !== undefined)
operation = makeOperation(b, prevOperation);
return operation();
}
};
};
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
::selection { background-color: #E13300; color: white; }
::-moz-selection { background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#body {
margin: 0 15px 0 15px;
}
p.footer {
text-align: right;
font-size: 11px;
border-top: 1px solid #D0D0D0;
line-height: 32px;
padding: 0 10px 0 10px;
margin: 20px 0 0 0;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
box-shadow: 0 0 8px #D0D0D0;
}
</style>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".num").click(function(){
var oprator = $("#val2").val();
var one = $(this).val();
if (oprator=='') {
var val1 = $("#val1").val();
$("#val1").val(val1+one);
}else{
var val1 = $("#val3").val();
$("#val3").val(val1+one);
}
});
$(".opt").click(function(){
var plus = $(this).val();
$("#val2").val(plus);
});
$("#equle").click(function(){
var plus = $("#equle").val();
var v1 = $("#val1").val();
var v2 = $("#val2").val();
var v3 = $("#val3").val();
var v1int=parseInt(v1);
var v3int=parseInt(v3);
if (v2=="+") {
var z = v1int+v3int;
}else if(v2=="-"){
var z = v1int-v3int;
}
else if(v2=="*"){
var z = v1int*v3int;
}
else{
var z = v1int/v3int;
}
$("#val4").val(z);
});
});
</script
<body>
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
<div id="body">
<table>
<tr cospan="5">
<td colspan="2"><input type='text' name="val1" value="" id="val1"/></td>
<td colspan="1"><input type='text' name="val2" value="" id="val2"/></td>
<td colspan="1"><input type='text' name="val3" value="" id="val3"/></td>
<td colspan="1"><input type='text' name="val4" value="" id="val4"/></td></tr>
<tr>
<td><button type="button" class="num" id="one" value="1">1</button></td>
<td><button type="button" class="num" id="two" value="2">2</button></td>
<td><button type="button" class="num" id="three" value="3">3</button></td>
<td><button type="button" class="num" id="four" value="4">4</button</td>
<td><button type="button" class="num" id="five" value="5">5</button></td>
</tr>
<tr>
<td><button type="button" class="num" id="six" value="6">6</button></td>
<td><button type="button" class="num" id="seven" value="7">7</button></td>
<td><button type="button" class="num" id="eight" value="8">8</button></td>
<td><button type="button" class="num" id="nine" value="9">9</button></td>
<td><button type="button" class="num" id="ten" value="10">0</button></td>
</tr>
<tr>
<td><button type="button" id="plus" class="opt" value="+">+</button></td>
<td><button type="button" id="minus" class="opt" value="-">-</button></td>
<td><button type="button" id="mul" class="opt" value="*">*</button></td>
<td><button type="button" id="dev" class="opt" value="/">/</button></td>
<td><button type="button" id="equle" value="=">=</button></td>
</tr>
</table>
</div>
</div>
</body>
</html>
Related
i would like create a table, where one column would be variables and i want to have "+" and "-" buttons next to it. So when i click button "+" it would show number input and after submit, it would add to the value.
It works for one value, but do not get the other right, without copying whole script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table</title>
</head>
<style>
body {
background-color: lightslategray;
}
#PLA {
float: left;
width: 30%;
padding: 10px;
}
th, td {
border: 1px solid;
}
.header {
text-align: center;
font-size: 20px;
}
.celltext {
font-size: 15px;
}
.number {
text-align: center;
}
.vbutton {
background-color: gray;
border: 1px solid black;
border-radius: 6px;
color: white;
text-align: center;
text-decoration: none;
font-size: 10px;
padding: 0px;
margin-right: 4px;
width: 20px;
height: 20px;
float: right;
}
button:hover {
background-color: lightgray;
color: black;
}
.input {
padding: 0px;
width: 48px;
height: 16px;
font-size: 14px;
-webkit-appearance: none;
}
input[type = number] {
-moz-appearance: textfield;
}
input:focus {
border: 0px;
outline: 0px;
}
</style>
<body>
<table id="PLA">
<div>
PLA
<span id="test"></span>
<input type="number" class="input" id="nwpla" onchange="changewpla1()" onkeypress="return onlyNumberKey(event)">
</div>
<tr class="header">
<td>Barva</td>
<td>Výrobce</td>
<td>Hmotnost (g)</td>
<td>Cena (kg)</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla1">
<span id="wpla1"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla2">
<span id="wpla2"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
</table>
</body>
<script>
// test
test = document.getElementById("test");
// Weight of pla1
wpla1 = document.getElementById("wpla1");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla1weight = localStorage.pla1weight;
localStorage.setItem("pla1weight", pla1weight);
if (localStorage.pla1weight == "undefined" || localStorage.pla1weight == isNaN) {
localStorage.pla1weight = 0
pla1weight = 0;
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
else {
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
function changewpla1() {
x = parseInt(wpla1.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla1weight = x - y;
} else {
pla1weight = x + y;
}
wpla1.innerHTML = pla1weight;
wpla1.value = pla1weight;
localStorage.setItem("pla1weight", pla1weight);
nwpla.style.display = "none";
}
// Weight of pla2
wpla2 = document.getElementById("wpla2");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla2weight = localStorage.pla2weight;
localStorage.setItem("pla2weight", pla2weight);
if (localStorage.pla2weight == "undefined" || localStorage.pla2weight == isNaN) {
localStorage.pla2weight = 0
pla2weight = 0;
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
else {
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
function changewpla2() {
x = parseInt(wpla2.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla2weight = x - y;
} else {
pla2weight = x + y;
}
wpla2.innerHTML = pla2weight;
wpla2.value = pla2weight;
localStorage.setItem("pla2weight", pla2weight);
nwpla.style.display = "none";
}
function addpla() {
nwpla.value = 0;
p = 0;
nwpla.style.display = "";
}
function subpla() {
nwpla.value = 0
p = 1;
nwpla.style.display = "";
}
function onlyNumberKey(evt) {
var ASCIICode = (evt.which) ? evt.which : evt.keyCode
if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
return false;
return true;
}
</script>
</html>
Any idea?
I would like to have a database as last option. Every value would be saved in local storage.
Thanks.
I have this HTML table that works well when I sorted the hard-coded data, especially the first column, but after the sort, when CRUD operation happens (Add/Edit), it will call right away the arrTable.reverse() method. It will sort again right if we click the second column but not again after adding or editing the data.
**Update
**I just want that after I add or insert new row, I can only call the sort function, not the reverse.
cPrev = -1; // global var saves the previous c, used to
// determine if the same column is clicked again
function sortBy(c) {
rows = document.getElementById("data_table").rows.length - 1; // num of rows
columns = document.getElementById("data_table").rows[0].cells.length; // num of columns
arrTable = [...Array(rows)].map(e => Array(columns)); // create an empty 2d array
for (ro = 0; ro < rows; ro++) { // cycle through rows
for (co = 0; co < columns; co++) { // cycle through columns
// assign the value in each row-column to a 2d array by row-column
arrTable[ro][co] = document.getElementById("data_table").rows[ro].cells[co].innerHTML;
}
}
th = arrTable.shift(); // remove the header row from the array, and save it //c !== cPrev
// if (c === cPrev ){ // different column is clicked, so sort by the new column
if (c !== cPrev) { // different column is clicked, so sort by the new column
arrTable.sort(
function(a, b) {
if (a[c] === b[c]) {
return 0;
} else {
return (a[c] < b[c]) ? -1 : 1;
}
}
);
} else { // if the same column is clicked then reverse the array
arrTable.reverse();
}
cPrev = c; // save in previous c
arrTable.unshift(th); // put the header back in to the array
// cycle through rows-columns placing values from the array back into the html table
for (ro = 0; ro < rows; ro++) {
for (co = 0; co < columns; co++) {
document.getElementById("data_table").rows[ro].cells[co].innerHTML = arrTable[ro][co];
}
}
}
const removeSaveBtns = () => {
const saveBtns = document.querySelectorAll('.save');
saveBtns.forEach((btn, i) => {
btn.style.display = "none";
})
}
removeSaveBtns();
function edit_row(no) {
document.getElementById("edit_button" + no).style.display = "none";
document.getElementById("save_button" + no).style.display = "";
var name = document.getElementById("name_row" + no);
var name_data = name.innerHTML;
name.innerHTML = "<input type='text' id='name_text" + no + "' value='" + name_data + "'>";
}
function save_row(no) {
var name_val = document.getElementById("name_text" + no).value;
document.getElementById("name_row" + no).innerHTML = name_val;
document.getElementById("save_button" + no).style.display = "none";
document.getElementById("edit_button" + no).style.display = "";
}
function delete_row(no) {
document.getElementById("row" + no + "").outerHTML = "";
}
function addOne(button) {
console.log(button.nextElementSibling.innerHTML)
var spanEle = button.nextElementSibling;
var old = parseInt(spanEle.innerHTML)
spanEle.innerHTML = old + 1;
}
function add_row(no) {
var new_name = document.getElementById("new_name").value;
var new_city = document.getElementById("new_city").value;
if (new_name == "" || new_name == null) {
window.alert("Please Input Team");
return false;
}
var table = document.getElementById("data_table");
var table_len = (table.rows.length) - 1;
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'><td id='name_row" + table_len + "'>" + new_name + "</td><td id='name_city" + table_len + "'>" + new_city + "</td><td><input type='button' id='edit_button" + table_len + "' value='Edit' class='edit' onclick='edit_row(" + table_len + ")'> <input type='button' id='save_button" + table_len + "' value='Save' class='save' onclick='save_row(" + table_len + ")'> <input type='button' id='delete_button" + table_len + "' value='Delete' class='delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("new_name").value = "";
document.getElementById("new_city").value = "";
removeSaveBtns();
}
h1 {
font-size: 30px;
color: #fff;
text-transform: uppercase;
font-weight: 300;
text-align: center;
margin-bottom: 15px;
}
table {
width: 100%;
table-layout: fixed;
}
.tbl-header {
background-color: rgba(255, 255, 255, 0.3);
}
.tbl-content {
height: 300px;
overflow-x: auto;
margin-top: 0px;
border: 1px solid rgba(255, 255, 255, 0.3);
}
th {
padding: 10px 15px;
text-align: left;
font-weight: 500;
font-size: 12px;
color: #fff;
text-transform: uppercase;
}
td {
padding: 15px;
text-align: center;
vertical-align: middle;
font-weight: 300;
font-size: 12px;
color: #fff;
border-bottom: solid 1px rgba(255, 255, 255, 0.1);
}
#import url(https://fonts.googleapis.com/css?family=Roboto:400,500,300,700);
body {
background: -webkit-linear-gradient(left, #25c481, #25b7c4);
background: linear-gradient(to right, #25c481, #25b7c4);
font-family: 'Roboto', sans-serif;
}
section {
margin: 50px;
}
button {
background: linear-gradient(to bottom right, #EF4765, #FF9A5A);
border: 0;
border-radius: 12px;
color: #FFFFFF;
cursor: pointer;
display: inline-block;
font-family: -apple-system, system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
font-size: 16px;
font-weight: 500;
line-height: 2.5;
outline: transparent;
padding: 0 1rem;
text-align: center;
text-decoration: none;
transition: box-shadow .2s ease-in-out;
user-select: none;
-webkit-user-select: none;
touch-action: manipulation;
white-space: nowrap;
}
button:not([disabled]):focus {
box-shadow: 0 0 .25rem rgba(0, 0, 0, 0.5), -.125rem -.125rem 1rem rgba(239, 71, 101, 0.5), .125rem .125rem 1rem rgba(255, 154, 90, 0.5);
}
button:not([disabled]):hover {
box-shadow: 0 0 .25rem rgba(0, 0, 0, 0.5), -.125rem -.125rem 1rem rgba(239, 71, 101, 0.5), .125rem .125rem 1rem rgba(255, 154, 90, 0.5);
}
<h1>City</h1>
<div id="wrapper">
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<tbody>
<tr>
<th onclick="sortBy(0)">Countries</th>
<th onclick="sortBy(1)">City</th>
<th>Action</th>
</tr>
<tr id="row1">
<td id="name_row1">Germany</td>
<td id="name_city1">Berlin</td>
<td>
<input type="button" id="edit_button1" value="Edit" class="edit" onclick="edit_row('1')">
<input type="button" id="save_button1" value="Save" class="save" onclick="save_row('1')">
<input type="button" id="delete_button1" value="Delete" class="delete" onclick="delete_row('1')">
</td>
</tr>
<tr id="row2">
<td id="name_row2">Norway</td>
<td id="name_city2">Oslo</td>
<td>
<input type="button" id="edit_button2" value="Edit" class="edit" onclick="edit_row('2')">
<input type="button" id="save_button2" value="Save" class="save" onclick="save_row('2')">
<input type="button" id="delete_button2" value="Delete" class="delete" onclick="delete_row('2')">
</td>
</tr>
<tr id="row3">
<td id="name_row3">Brazil</td>
<td id="name_city3">Rio</td>
<td>
<input type="button" id="edit_button3" value="Edit" class="edit" onclick="edit_row('3')">
<input type="button" id="save_button3" value="Save" class="save" onclick="save_row('3')">
<input type="button" id="delete_button3" value="Delete" class="delete" onclick="delete_row('3')">
</td>
</tr>
<tr id="row4">
<td id="name_row4">Mexico</td>
<td id="name_city4">MX</td>
<td>
<input type="button" id="edit_button4" value="Edit" class="edit" onclick="edit_row('4')">
<input type="button" id="save_button4" value="Save" class="save" onclick="save_row('4')">
<input type="button" id="delete_button4" value="Delete" class="delete" onclick="delete_row('4')">
</td>
</tr>
<tr id="row4">
<td id="name_row5">Bahamas</td>
<td id="name_city5">Nassau</td>
<td>
<input type="button" id="edit_button5" value="Edit" class="edit" onclick="edit_row('5')">
<input type="button" id="save_button5" value="Save" class="save" onclick="save_row('5')">
<input type="button" id="delete_button5" value="Delete" class="delete" onclick="delete_row('5')">
</td>
</tr>
<tr>
<td><input type="text" id="new_name"></td>
<td><input type="text" id="new_city"></td>
<td><input type="button" class="add" onclick="add_row();" value="Add Row"></td>
</tr>
</tbody>
</table>
</div>
Thanks a lot.
I have two things that relate to adding a character to the output view.
Pronouns - Right now, it is hidden until someone types in their preferred pronoun. It'll output her/she if that's what they put, but I would like to do '(' + "her/she" + ')';
2.The output is hidden until someone types a number. I would like to have it as display M: 739.383.3893.
I can get the outputs to display the input text but never the with the character. How do I go about adding characters into the output based on the input the user puts in?
Extreme beginner here, I'm sorry :(
(function() {
/*
* Input stuff
*/
var doc = document;
var form = doc.getElementById('form');
var copyButton = doc.getElementById('copy');
var resetButton = doc.getElementById('reset');
var inputPhone = doc.getElementById('phone');
var inputOffice = doc.getElementById('office');
var instructions = doc.getElementById('instructions');
var inputFullName = doc.getElementById('fullName');
var inputPronouns = doc.getElementById('pronouns');
var inputJobTitle = doc.getElementById('jobTitle');
var copyButtonOriginalHTML = '<i class="fas fa-copy"></i> Copy Signature';
var copyButtonDisabledHTML = '<i class="fas fa-exclamation-circle"></i> Enter your info first!';
var peopleTemplate = {
empty: {
fullName: "",
pronouns: "",
jobTitle: "",
phone: "",
office: ""
},
dummy: {
fullName: "Your Name",
jobTitle: "Your title",
pronouns: "Your pronouns",
office: "7890",
phone: "123-456-7890"
}
};
/*
* Output stuff
*/
var sig = doc.getElementById('sig');
var sigPhone = doc.querySelector('.sig__phone');
var sigFullName = doc.querySelector('.sig__fullName');
var sigJobTitle = doc.querySelector('.sig__jobTitle');
var sigPronouns = doc.querySelector('.sig__pronouns');
var sigOffice = doc.querySelector('.sig__office');
/*
* Instructions HTML
*/
var pasteInstructions = "<h3>Yay! Your signature was copied and is ready to paste.</h3>"
+ "<p>To create a new signature in Outlook, follow these directions:</p>"
+ "<ol><li>Update Outlook to the latest version.</li>"
+ "<li>Open Outlook.</li>"
+ "<li>Under <b>Outlook</b> in the main menu, select <b>Preferences</b>.</li>"
+ "<li>Under the <b>Email</b> section, click <b>Signatures</b>.</li>"
+ "<li>In the <b>Edit Signatures</b> section, click the <b>+</b> (plus) icon in the bottom left corner.</li>"
+ "<li>Select whatever is there already and paste your new signature into the box.</li>"
+ "</ol>";
/*
* Clear form inputs
*/
var resetForm = function () {
inputFullName.value = '';
inputJobTitle.value = '';
inputPhone.value = '';
inputPronouns.value = '';
inputOffice.value = '';
updateSignature();
instructions.innerHTML = '';
};
/*
* Fill signature with dummy info
*/
var fillDummySignature = function () {
sigFullName.textContent = "Your Name";
sigPronouns.textContent = ""
sigJobTitle.textContent = "Your title";
sigPhone.textContent = "";
sigOffice.textContent = "1234";
};
/*
* Check if nothing is entered
*/
var inputsAreEmpty = function () {
return inputFullName.value === ''
&& inputPronouns.value === ''
&& inputJobTitle.value === ''
&& inputPhone.value === ''
&& inputOffice.value === '';
};
var userName = document.querySelector('#phone');
userName.addEventListener('input', restrictNumber);
function restrictNumber (e) {
var newValue = this.value.replace(new RegExp(/[^\d]/,'ig'), "");
this.value = newValue;
}
/*
* Reformat phone number syntax
*/
var formatPhone = function (n) {
// var pattern = /[^0-9.]+/g;
// if (n.search(pattern) !== -1) {
// console.log("not a number");
// // n.replace(pattern, '');
// return n;
// }
var o = n;
var l = n.length;
var noDash = function (value, index) {
return value.charAt(index) !== '.';
};
var insertDash = function (value, index) {
return value.slice(0, index) + '.' + value.slice(index, value.length + 1);
};
var no3 = noDash(o, 3);
var no7 = noDash(o, 7);
if (l > 3 && l <= 7) {
if (no3) {
o = insertDash(n, 3);
}
} else if (l > 7 && l <= 11) {
if (no3) {
o = insertDash(n, 3);
if (no7) {
o = insertDash(o, 7); // insert on the value we just updated
}
} else if (no7) {
o = insertDash(n, 7);
}
} else if (l > 12) {
o = n.slice(0, 12);
}
return o;
};
/*
* Add the input values into the actual signature
*/
var updateSignature = function (event) {
if (inputsAreEmpty()) {
fillDummySignature();
// Button states
copyButton.disabled = true;
copyButton.innerHTML = copyButtonDisabledHTML;
resetButton.style.display = 'none';
} else {
// Button states
copyButton.disabled = false;
copyButton.innerHTML = copyButtonOriginalHTML;
resetButton.style.display = 'inline-block';
// Populate signature fields
if (event && event.target.tagName === 'INPUT') {
var id = event.target.id;
var input = doc.getElementById(id);
var sigClassName = '.sig__' + id;
var inputIdName = '#' + id;
var sigTarget = doc.querySelector(sigClassName);
var inputTarget = doc.querySelector(inputIdName);
if (id === 'fullName') {
sigTarget.textContent = input.value;
} else if (id === 'phone') {
sigTarget.textContent = formatPhone(input.value);
inputTarget.value = formatPhone(input.value);
} else {
sigTarget.textContent = input.value;
}
} else {
sigFullName.textContent = inputFullName.value;
sigJobTitle.textContent = inputJobTitle.value;
sigPhone.textContent = inputPhone.value;
}
}
}
/*
* Insert a person's info when option is selected
*/
var insertPersonInfo = function (event) {
resetForm();
if (event.target.value !== 'custom') {
var person = people[this.selectedIndex - 1];
inputFullName.value = person.fullName;
inputPronouns.value = person.pronouns;
inputJobTitle.value = person.jobTitle;
inputPhone.value = person.phone;
updateSignature(event);
}
};
/*
* Populate the people info in the select menu on load
*/
document.addEventListener("DOMContentLoaded", function (event) {
updateSignature(event);
fillDummySignature();
});
/*
* Copy raw HTML output
*/
copyButton.addEventListener('click', function(event) {
// Have to remove any existing ranges :: Chrome bug
window.getSelection().removeAllRanges();
// Create range and add it to selection
var r = document.createRange();
r.selectNode(sig);
window.getSelection().addRange(r);
// Error catching
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy');
}
// Remove range from selection again
window.getSelection().removeAllRanges();
if (successful) {
instructions.innerHTML = pasteInstructions;
// this.parentNode.removeChild(this);
}
});
/*
* Listeners
*/
form.addEventListener('input', updateSignature);
resetButton.addEventListener('click', resetForm);
inputPhone.addEventListener('paste', function(event) {
// formatPhone();
});
}());
.form__input, .button, .button--copy, .button--reset {
font-size: 14px;
margin: 0;
padding: 6px 9px;
border: 1px solid #e7e7e7;
border-radius: 2px;
line-height: 1;
}
* {
box-sizing: border-box;
}
.sig-gen {
font-family: 'Work Sans', 'Helvetica Neue', Arial, sans-serif;
font-size: 16px;
margin: 2em auto 4em;
width: 100%;
max-width: 800px;
}
.sig-gen__section {
margin-bottom: 2em;
}
.sig-gen__section--email {
margin-bottom: 3em;
}
.sig__field, .set-inform, .links-text {
font-family: 'Work Sans', 'Helvetica Neue', Arial, sans-serif;
}
.form {
display: flex;
justify-content: space-between;
flex-direction: column;
}
.set-inform {
display: inline-block;
}
#media screen and (min-width: 600px) {
.form {
/* flex-direction: row; */
}
}
.form__group {
margin-bottom: 12px;
}
.form__group:last-of-type {
margin-bottom: 0;
}
#media screen and (min-width: 600px) {
.form__group {
margin-bottom: 10px;
}
}
.form label {
display: block;
margin-bottom: 6px;
}
.form__input {
background: white;
width: 100%;
}
.form__input:focus, .form__input:active {
outline: 0;
border-color: #bebebe;
}
.email_generator {
position: relative;
border: 1px solid #e7e7e7;
border-top: none;
border-bottom: none;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
box-shadow: 0 6px 0 #ccc;
}
.email_generator:before {
content: "";
position: absolute;
top: 0;
left: -1px;
width: calc(100% + 2 * 1px);
height: 28%;
background: linear-gradient(white, rgba(255, 255, 255, 0));
}
.email__container {
padding: 28px;
}
.email__sig {
margin-top: 51px;
}
.email__line {
height: 12px;
margin-bottom: 12px;
background: #e7e7e7;
border-radius: 1px;
}
.email__line:last-child {
width: 66%;
margin-bottom: 28px;
}
.email__signoff .email__line {
width: 17%;
}
.sig__field {
font-size: 14px;
}
.sig__fullName {
font-size: 18px;
}
.button, .button--copy, .button--reset {
padding: 9px 12px;
color: white;
cursor: pointer;
background: #8c4049;
border-color: #823b44;
}
.button:hover, .button--copy:hover, .button--reset:hover {
background: #97454e;
border-color: #8c4049;
}
.button:focus, .button--copy:focus, .button--reset:focus, .button:active, .button--copy:active, .button--reset:active {
outline: 0;
background: #77363e;
border-color: #622d33;
}
.button:disabled, .button--copy:disabled, .button--reset:disabled {
background: #656669;
border-color: #5d5e61;
cursor: not-allowed;
color: white;
}
.button--reset {
background: #e2e3e4;
border-color: #dadbdd;
color: #656669;
}
.button--reset:hover {
background: #eaebeb;
border-color: #e2e3e4;
}
.button--reset:focus, .button--reset:active {
outline: 0;
background: #d2d4d5;
border-color: #c2c4c6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="app" class="sig-gen">
<section class="sig-gen__section">
<h2>Email Signature Generator</h2>
</section>
<section class="sig-gen__section">
<form id="form" class="form">
<div class="form__group">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" class="form__input" placeholder="Your name" value="">
</div>
<div class="form__group">
<label for="pronouns">Pronouns:</label>
<input type="text" id="pronouns" class="form__input" placeholder="optional (they/them)" value="">
</div>
<div class="form__group">
<label for="jobTitle">Job Title:</label>
<input type="text" id="jobTitle" class="form__input" placeholder="Your title" value="">
</div>
<div class="form__group">
<label for="office">Office Extension:</label>
<input type="text" id="office" class="form__input" pattern="[0-9]" maxlength="4" placeholder="1234" value="">
</div>
<div class="form__group">
<label for="phone">Mobile:</label>
<input type="text" id="phone" class="form__input" pattern="[0-9]" maxlength="12" placeholder="optional" value="">
</div>
</form>
</section>
<section class="sig-gen__section sig-gen__section--email">
<div class="email_generator">
<div class="email__container">
<div id="sig" class="email__sig">
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;font-family:Helvetica,'Helvetica Neue',Arial,sans-serif;font-size:16px;font-weight:normal;color:#313030;line-height:1.5;">
<tbody border="0" cellpadding="0" cellspacing="0">
<tr border="0" cellpadding="0" cellspacing="0">
<td align="left" height="28" style="mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;font-family:Arial,sans-serif;font-size:16px;font-weight:normal;color:#313030;line-height:1.5;" valign="top">
<div>
<strong class="sig__field sig__fullName set-inform" style="font-size: 16px; color:#002857;"></strong><div class="sig__field sig__pronouns set-inform" style="font-size: 13px; color: #002857; font-style: italic;"></div>
</div>
<div class="sig__field sig__jobTitle" style="font-size: 15px; color: #7f7f7f"></div>
<div class="links-text" style="font-size: 15px; color: #7f7f7f">3847 New York, New York</div>
<div class="set-inform" style="font-size: 15px; color: #7f7f7f">O: 383.384.4838 ext.</div><div class="sig__field sig__office set-inform" style="font-size: 15px; color: #7f7f7f"></div><span> </span><div class="sig__phone set-inform" style="font-size: 15px; color: #7f7f7f"></div>
<div class="links-text" style="font-size: 15px;"><a style="color: #7f7f7f;" href="#">FB</a> | <a style="color: #7f7f7f;" href="#">Twitter</a> | <a style="color: #7f7f7f;" href="#">Instagram</a> | <a style="color: #7f7f7f;" href="#">LinkedIn</a></div>
</td>
</tr>
<tr border="0" cellpadding="0" cellspacing="0">
<td align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;font-family:Arial,sans-serif;font-size:16px;font-weight:normal;color:#313030;line-height:1.5;margin:0;padding:0;" valign="top">
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;font-family:Helvetica,'Helvetica Neue',Arial,sans-serif;font-size:16px;font-weight:normal;color:#313030;line-height:1.5;">
<tbody border="0" cellpadding="0" cellspacing="0">
<tr border="0" cellpadding="0" cellspacing="0">
<td align="left" style="mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;line-height:1.4;" valign="top">
New York University<span style="margin-left:10px;margin-right: 10px;border-left: solid; border-color: #002857;border-width: 2px;"></span><span style="font-weight: bold;color: #C20F2F;font-size:18px;letter-spacing: 1px;"> NYU</span>
</td>
</tr>
<tr border="0" cellpadding="0" cellspacing="0">
<td align="left" height="16" style="mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;" valign="top">
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</section>
<section class="sig-gen__section">
<button id="copy" class="button--copy"></button>
<button id="reset" class="button--reset"><i class="fas fa-sync"></i> Reset Form</button>
</section>
<section class="sig-gen__section">
<div id="instructions"></div>
</section>
</div>
[x] displaying of (pronoun) is done,
[x] prepending M. to the displayed mobile number is done,
(function() {
/*
* Input stuff
*/
var doc = document;
var form = doc.getElementById('form');
var copyButton = doc.getElementById('copy');
var resetButton = doc.getElementById('reset');
var inputPhone = doc.getElementById('phone');
var inputOffice = doc.getElementById('office');
var instructions = doc.getElementById('instructions');
var inputFullName = doc.getElementById('fullName');
var inputPronouns = doc.getElementById('pronouns');
var inputJobTitle = doc.getElementById('jobTitle');
var copyButtonOriginalHTML = '<i class="fas fa-copy"></i> Copy Signature';
var copyButtonDisabledHTML = '<i class="fas fa-exclamation-circle"></i> Enter your info first!';
var peopleTemplate = {
empty: {
fullName: "",
pronouns: "",
jobTitle: "",
phone: "",
office: ""
},
dummy: {
fullName: "Your Name",
jobTitle: "Your title",
pronouns: "Your pronouns",
office: "7890",
phone: "123-456-7890"
}
};
/*
* Output stuff
*/
var sig = doc.getElementById('sig');
var sigPhone = doc.querySelector('.sig__phone');
var sigFullName = doc.querySelector('.sig__fullName');
var sigJobTitle = doc.querySelector('.sig__jobTitle');
var sigPronouns = doc.querySelector('.sig__pronouns');
var sigOffice = doc.querySelector('.sig__office');
/*
* Instructions HTML
*/
var pasteInstructions = "<h3>Yay! Your signature was copied and is ready to paste.</h3>" +
"<p>To create a new signature in Outlook, follow these directions:</p>" +
"<ol><li>Update Outlook to the latest version.</li>" +
"<li>Open Outlook.</li>" +
"<li>Under <b>Outlook</b> in the main menu, select <b>Preferences</b>.</li>" +
"<li>Under the <b>Email</b> section, click <b>Signatures</b>.</li>" +
"<li>In the <b>Edit Signatures</b> section, click the <b>+</b> (plus) icon in the bottom left corner.</li>" +
"<li>Select whatever is there already and paste your new signature into the box.</li>" +
"</ol>";
/*
* Clear form inputs
*/
var resetForm = function() {
inputFullName.value = '';
inputJobTitle.value = '';
inputPhone.value = '';
inputPronouns.value = '';
inputOffice.value = '';
updateSignature();
instructions.innerHTML = '';
};
/*
* Fill signature with dummy info
*/
var fillDummySignature = function() {
sigFullName.textContent = "Your Name";
sigPronouns.textContent = ""
sigJobTitle.textContent = "Your title";
sigPhone.textContent = "";
sigOffice.textContent = "1234";
};
/*
* Check if nothing is entered
*/
var inputsAreEmpty = function() {
return [inputFullName, inputPronouns, inputJobTitle, inputPhone, inputOffice].every(({
value
}) => value === '')
};
var userName = document.querySelector('#phone');
userName.addEventListener('input', restrictNumber);
function restrictNumber(e) {
var newValue = this.value.replace(new RegExp(/[^\d]/, 'ig'), "");
this.value = newValue;
}
/*
* Reformat phone number syntax
*/
var formatPhone = function(n) {
// var pattern = /[^0-9.]+/g;
// if (n.search(pattern) !== -1) {
// console.log("not a number");
// // n.replace(pattern, '');
// return n;
// }
var o = n;
var l = n.length;
var noDash = function(value, index) {
return value.charAt(index) !== '.';
};
var insertDash = function(value, index) {
return value.slice(0, index) + '.' + value.slice(index, value.length + 1);
};
var no3 = noDash(o, 3);
var no7 = noDash(o, 7);
if (l > 3 && l <= 7) {
if (no3) {
o = insertDash(n, 3);
}
} else if (l > 7 && l <= 11) {
if (no3) {
o = insertDash(n, 3);
if (no7) {
o = insertDash(o, 7); // insert on the value we just updated
}
} else if (no7) {
o = insertDash(n, 7);
}
} else if (l > 12) {
o = n.slice(0, 12);
}
return o;
};
/*
* Add the input values into the actual signature
*/
var updateSignature = function(event) {
if (inputsAreEmpty()) {
fillDummySignature();
// Button states
copyButton.disabled = true;
copyButton.innerHTML = copyButtonDisabledHTML;
resetButton.style.display = 'none';
} else {
// Button states
copyButton.disabled = false;
copyButton.innerHTML = copyButtonOriginalHTML;
resetButton.style.display = 'inline-block';
// Populate signature fields
if (event && event.target.tagName === 'INPUT') {
var id = event.target.id;
var input = doc.getElementById(id);
var sigClassName = '.sig__' + id;
var inputIdName = '#' + id;
var sigTarget = doc.querySelector(sigClassName);
var inputTarget = doc.querySelector(inputIdName);
if (id === 'fullName') {
sigTarget.textContent = input.value;
} else if (id === 'phone') {
// just save the value in a variable, and use that
const formattedPhone = formatPhone(input.value);
sigTarget.textContent = `M. ${formattedPhone}`;
inputTarget.value = formattedPhone
} else if (id === 'pronouns') {
// this case needed to be treated separately
sigTarget.textContent = `(${input.value})`
} else {
sigTarget.textContent = input.value;
}
} else {
sigFullName.textContent = inputFullName.value;
sigJobTitle.textContent = inputJobTitle.value;
sigPhone.textContent = inputPhone.value;
}
}
}
/*
* Insert a person's info when option is selected
*/
var insertPersonInfo = function(event) {
resetForm();
if (event.target.value !== 'custom') {
var person = people[this.selectedIndex - 1];
inputFullName.value = person.fullName;
inputPronouns.value = person.pronouns;
inputJobTitle.value = person.jobTitle;
inputPhone.value = person.phone;
updateSignature(event);
}
};
/*
* Populate the people info in the select menu on load
*/
document.addEventListener("DOMContentLoaded", function(event) {
updateSignature(event);
fillDummySignature();
});
/*
* Copy raw HTML output
*/
copyButton.addEventListener('click', function(event) {
// Have to remove any existing ranges :: Chrome bug
window.getSelection().removeAllRanges();
// Create range and add it to selection
var r = document.createRange();
r.selectNode(sig);
window.getSelection().addRange(r);
// Error catching
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
// Remove range from selection again
window.getSelection().removeAllRanges();
if (successful) {
instructions.innerHTML = pasteInstructions;
// this.parentNode.removeChild(this);
}
});
/*
* Listeners
*/
form.addEventListener('input', updateSignature);
resetButton.addEventListener('click', resetForm);
inputPhone.addEventListener('paste', function(event) {
// formatPhone();
});
}());
.form__input,
.button,
.button--copy,
.button--reset {
font-size: 14px;
margin: 0;
padding: 6px 9px;
border: 1px solid #e7e7e7;
border-radius: 2px;
line-height: 1;
}
* {
box-sizing: border-box;
}
.sig-gen {
font-family: 'Work Sans', 'Helvetica Neue', Arial, sans-serif;
font-size: 16px;
margin: 2em auto 4em;
width: 100%;
max-width: 800px;
}
.sig-gen__section {
margin-bottom: 2em;
}
.sig-gen__section--email {
margin-bottom: 3em;
}
.sig__field,
.set-inform,
.links-text {
font-family: 'Work Sans', 'Helvetica Neue', Arial, sans-serif;
}
.form {
display: flex;
justify-content: space-between;
flex-direction: column;
}
.set-inform {
display: inline-block;
}
#media screen and (min-width: 600px) {
.form {
/* flex-direction: row; */
}
}
.form__group {
margin-bottom: 12px;
}
.form__group:last-of-type {
margin-bottom: 0;
}
#media screen and (min-width: 600px) {
.form__group {
margin-bottom: 10px;
}
}
.form label {
display: block;
margin-bottom: 6px;
}
.form__input {
background: white;
width: 100%;
}
.form__input:focus,
.form__input:active {
outline: 0;
border-color: #bebebe;
}
.email_generator {
position: relative;
border: 1px solid #e7e7e7;
border-top: none;
border-bottom: none;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
box-shadow: 0 6px 0 #ccc;
}
.email_generator:before {
content: "";
position: absolute;
top: 0;
left: -1px;
width: calc(100% + 2 * 1px);
height: 28%;
background: linear-gradient(white, rgba(255, 255, 255, 0));
}
.email__container {
padding: 28px;
}
.email__sig {
margin-top: 51px;
}
.email__line {
height: 12px;
margin-bottom: 12px;
background: #e7e7e7;
border-radius: 1px;
}
.email__line:last-child {
width: 66%;
margin-bottom: 28px;
}
.email__signoff .email__line {
width: 17%;
}
.sig__field {
font-size: 14px;
}
.sig__fullName {
font-size: 18px;
}
.button,
.button--copy,
.button--reset {
padding: 9px 12px;
color: white;
cursor: pointer;
background: #8c4049;
border-color: #823b44;
}
.button:hover,
.button--copy:hover,
.button--reset:hover {
background: #97454e;
border-color: #8c4049;
}
.button:focus,
.button--copy:focus,
.button--reset:focus,
.button:active,
.button--copy:active,
.button--reset:active {
outline: 0;
background: #77363e;
border-color: #622d33;
}
.button:disabled,
.button--copy:disabled,
.button--reset:disabled {
background: #656669;
border-color: #5d5e61;
cursor: not-allowed;
color: white;
}
.button--reset {
background: #e2e3e4;
border-color: #dadbdd;
color: #656669;
}
.button--reset:hover {
background: #eaebeb;
border-color: #e2e3e4;
}
.button--reset:focus,
.button--reset:active {
outline: 0;
background: #d2d4d5;
border-color: #c2c4c6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="app" class="sig-gen">
<section class="sig-gen__section">
<h2>Email Signature Generator</h2>
</section>
<section class="sig-gen__section">
<form id="form" class="form">
<div class="form__group">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" class="form__input" placeholder="Your name" value="">
</div>
<div class="form__group">
<label for="pronouns">Pronouns:</label>
<input type="text" id="pronouns" class="form__input" placeholder="optional (they/them)" value="">
</div>
<div class="form__group">
<label for="jobTitle">Job Title:</label>
<input type="text" id="jobTitle" class="form__input" placeholder="Your title" value="">
</div>
<div class="form__group">
<label for="office">Office Extension:</label>
<input type="text" id="office" class="form__input" pattern="[0-9]" maxlength="4" placeholder="1234" value="">
</div>
<div class="form__group">
<label for="phone">Mobile:</label>
<input type="text" id="phone" class="form__input" pattern="[0-9]" maxlength="12" placeholder="optional" value="">
</div>
</form>
</section>
<section class="sig-gen__section sig-gen__section--email">
<div class="email_generator">
<div class="email__container">
<div id="sig" class="email__sig">
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;font-family:Helvetica,'Helvetica Neue',Arial,sans-serif;font-size:16px;font-weight:normal;color:#313030;line-height:1.5;">
<tbody border="0" cellpadding="0" cellspacing="0">
<tr border="0" cellpadding="0" cellspacing="0">
<td align="left" height="28" style="mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;font-family:Arial,sans-serif;font-size:16px;font-weight:normal;color:#313030;line-height:1.5;" valign="top">
<div>
<strong class="sig__field sig__fullName set-inform" style="font-size: 16px; color:#002857;"></strong>
<div class="sig__field sig__pronouns set-inform" style="font-size: 13px; color: #002857; font-style: italic;"></div>
</div>
<div class="sig__field sig__jobTitle" style="font-size: 15px; color: #7f7f7f"></div>
<div class="links-text" style="font-size: 15px; color: #7f7f7f">3847 New York, New York</div>
<div class="set-inform" style="font-size: 15px; color: #7f7f7f">O: 383.384.4838 ext.</div>
<div class="sig__field sig__office set-inform" style="font-size: 15px; color: #7f7f7f"></div><span> </span>
<div class="sig__phone set-inform" style="font-size: 15px; color: #7f7f7f"></div>
<div class="links-text" style="font-size: 15px;"><a style="color: #7f7f7f;" href="#">FB</a> | <a style="color: #7f7f7f;" href="#">Twitter</a> | <a style="color: #7f7f7f;" href="#">Instagram</a> | <a style="color: #7f7f7f;" href="#">LinkedIn</a></div>
</td>
</tr>
<tr border="0" cellpadding="0" cellspacing="0">
<td align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;font-family:Arial,sans-serif;font-size:16px;font-weight:normal;color:#313030;line-height:1.5;margin:0;padding:0;" valign="top">
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;font-family:Helvetica,'Helvetica Neue',Arial,sans-serif;font-size:16px;font-weight:normal;color:#313030;line-height:1.5;">
<tbody border="0" cellpadding="0" cellspacing="0">
<tr border="0" cellpadding="0" cellspacing="0">
<td align="left" style="mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;line-height:1.4;" valign="top">
New York University
<span style="margin-left:10px;margin-right: 10px;border-left: solid; border-color: #002857;border-width: 2px;"></span><span style="font-weight: bold;color: #C20F2F;font-size:18px;letter-spacing: 1px;"> NYU</span>
</td>
</tr>
<tr border="0" cellpadding="0" cellspacing="0">
<td align="left" height="16" style="mso-table-lspace:0pt;mso-table-rspace:0pt;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;" valign="top">
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</section>
<section class="sig-gen__section">
<button id="copy" class="button--copy"></button>
<button id="reset" class="button--reset"><i class="fas fa-sync"></i> Reset Form</button>
</section>
<section class="sig-gen__section">
<div id="instructions"></div>
</section>
</div>
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
}
I am a beginner and trying to write a simple Calculator in Javascript but something is wrong.
When the user enters numbers, "Number 1" and "Number 2", then the following should occur for addition, subtraction, multiply and division (for example):
Number1 = 5, Number2 = 3
then => 5 + 3 = 8,
5 - 3 = 2,
5 * 3 = 15,
5 / 3 = 1.6
When the user gives numbers to specific equation, then displays the result of these operations.
<html>
<head>
<title>Function Calculator</title>
<script type="text/javascript">
function show_cal(){
function num(){
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a+b;
document.form1.result1.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a-b;
document.form1.result2.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a*b;
document.form1.result3.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a/b;
document.form1.result4.value=c;
}
function addition(){
a=Number(document.form1.num3.value);
b=Number(document.form1.num4.value);
c=a+b;
document.form1.result1.value=c;
}
function subtraction(){
a=Number(document.form1.num5.value);
b=Number(document.form1.num6.value);
c=a-b;
document.form1.result2.value=c;
}
function multiply(){
a=Number(document.form1.num7.value);
b=Number(document.form1.num8.value);
c=a*b;
document.form1.result3.value=c;
}
function division(){
a=Number(document.form1.num9.value);
b=Number(document.form1.num10.value);
c=a/b;
document.form1.result4.value=c;
}
/*function formValidator(){
var number = document.getElementById('number');
if(isNumeric(number, "Only Numbers pls")){
return true;
}return false;
}
function notEmpty(elem, helperMsg){ //gia keno
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function show_clear(){
document.form1.display.value=null;
num1= null;
num2 = null;
lastaction= null;
action = null;
} */
}
</script>
</head>
<body>
<table width="400" align="center" bgcolor="#C0C0C0">
<form name="form1" action="">
<tr align="center">
<td width="600" height="112" align="center" border="1">
<h1 align="center"> Calculator </h1>
Number 1: <input name="num1" type="text" size=10/>
Number 2: <input name="num2" type="text" size=10/>
</td>
</tr>
<tr align="center">
<td width="500">
<input name="num3" type="text" size=10/> +
<input name="num4" type="text" size=10/> =
<input name="result1" type="text" size=10/>
</td>
</tr>
<br/>
<tr align="center">
<td width="500">
<input name="num5" type="text" size=10/> -
<input name="num6" type="text" size=10/> =
<input name="result2" type="text" size=10/>
</td>
</tr>
<br/>
<tr align="center">
<td width="500">
<input name="num7" type="text" size=10/> *
<input name="num8" type="text" size=10/> =
<input name="result3" type="text" size=10/>
</td>
</tr>
<br/>
<tr align="center">
<td width="500">
<input name="num9" type="text" size=10/> /
<input name="num10" type="text"size=10/> =
<input name="result4" type="text" size=10/>
</td>
</tr>
<br/>
<td height="13"></tr>
<tr align="center" width="100">
<td>
<input name="result" type="button" onClick="show_cal()" value="Result" />
<input type="button" onClick="show_clear()" value="Clear"/>
</td>
</tr>
</form>
</table>
</body>
</html>
the problem is you have a function sum within a function show_calc and you don't call this function.
You need call the function num when finish the showcalc function.
<script type="text/javascript">
function show_cal(){
function num(){
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a+b;
document.form1.result1.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a-b;
document.form1.result2.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a*b;
document.form1.result3.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a/b;
document.form1.result4.value=c;
}
function addition(){
a=Number(document.form1.num3.value);
b=Number(document.form1.num4.value);
c=a+b;
document.form1.result1.value=c;
}
function subtraction(){
a=Number(document.form1.num5.value);
b=Number(document.form1.num6.value);
c=a-b;
document.form1.result2.value=c;
}
function multiply(){
a=Number(document.form1.num7.value);
b=Number(document.form1.num8.value);
c=a*b;
document.form1.result3.value=c;
}
function division(){
a=Number(document.form1.num9.value);
b=Number(document.form1.num10.value);
c=a/b;
document.form1.result4.value=c;
}
num();
}
But I better ways to make this correctly.
Your code could be cleaner and violates DRY (Don't Repeat Yourself) repeatedly.
Try this:
<form action="javascript:void(null);" method="post" onSubmit="calculate(this);">
<p><label>Number 1: <input type="number" /></label></p>
<p><label>Number 2: <input type="number" /></label></p>
<p><input type="submit" value="Calculate" /></p>
<p>N1 + N2 = <span>-</span></p>
<p>N1 - N2 = <span>-</span></p>
<p>N1 * N2 = <span>-</span></p>
<p>N1 / N2 = <span>-</span></p>
</form>
<script type="text/javascript">
function calculate(form) {
var fc = form.children,
n1 = parseInt(fc[0].children[0].children[0].value || 0,10),
n2 = parseInt(fc[1].children[0].children[0].value || 0,10);
fc[3].children[0].firstChild.nodeValue = n1+n2;
fc[4].children[0].firstChild.nodeValue = n1-n2;
fc[5].children[0].firstChild.nodeValue = n1*n2;
fc[6].children[0].firstChild.nodeValue = n1/n2;
}
</script>
JSFiddle demonstration
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<link rel="stylesheet" href="cal.css">
<script src="./calc.js"></script>
</head>
<body>
<div class="calculator">
<div id="textBox1">
<input type="text"id="textBox" placeholder="0"/>
</div>
<div class="buttons">
<button class="calc-buttons" onclick="disPlay('1')" value="1">1</button>
<button class="calc-buttons" onclick="disPlay('2')" value="2">2</button>
<button class="calc-buttons" onclick="disPlay('3')" value="3">3</button>
<button class="calc-buttons" onclick="disPlay('4')" value="4">4</button>
<button class="calc-buttons" onclick="disPlay('5')" value="5">5</button>
<button class="calc-buttons" onclick="disPlay('6')" value="6">6</button>
<button class="calc-buttons" onclick="disPlay('7')" value="7">7</button>
<button class="calc-buttons" onclick="disPlay('8')" value="8">8</button>
<button class="calc-buttons" onclick="disPlay('9')" value="9">9</button>
<button class="calc-buttons" onclick="disPlay('0')" value="0">0</button>
<button class="calc-buttons" onclick="disPlay('+')" value="+">+</button>
<button class="calc-buttons" onclick="disPlay('-')" value="-">-</button>
<button class="calc-buttons" onclick="disPlay('*')" value="*">*</button>
<button class="calc-buttons" onclick="disPlay('/')" value="/">/</button>
<button class="calc-buttons" onclick="disPlay('%')" value="%">%</button>
<button class="calc-buttons" onclick="clr()" value="clear">C</button>
<button class="calc-buttons" onclick="disPlay('.')" value=".">.</button>
<button class="calc-buttons" onclick="backSpace()" value="B">B</button>
<button class="calc-buttons-equal" onclick="result()" value="=">=</button>
</div>
</div>
</body>
</html>
calc.js:---
var res = "";
function disPlay(x) {
nan = document.getElementById("textBox").value;
if (nan === "NaN" || nan === "Infinity" || nan === "undefined" || nan === "-Infinity") { // delete Nan,infinity,undefined after entering the numbers.
document.getElementById("textBox").value = "";
}
if (res && (x >= 0 || x <= 0)) {
res = false;
document.getElementById("textBox").value = "";
document.getElementById("textBox").value += x;
} else {
document.getElementById("textBox").value += x;
res = false;
var y = [];
y = document.getElementById("textBox").value;
p = y.length;
if ((y[p - 2] === "*" || y[p - 2] === "/" || y[p - 2] === "%" || y[p - 2] === "+" || y[p - 2] === "-" || y[p - 2] === ".") && (x === "*" || x === "/" || x === "%" || x === "+" || x === "-" || x === ".")) {
document.getElementById("textBox").value = y.slice(0, p - 1);
}
}
}
function clr() {
document.getElementById("textBox").value = "";
}
function backSpace() {
bakSpa = document.getElementById("textBox").value;
if (bakSpa === "NaN" || bakSpa === "Infinity" || bakSpa === "undefined" || bakSpa === "-Infinity") {
document.getElementById("textBox").value = "";
} else {
var value = document.getElementById("textBox").value;`enter code here`
document.getElementById("textBox").value = value.substr(0, value.length - 1);
}
}
function result() {
exp = "";
exp = document.getElementById("textBox").value;
l = exp.length;
if (exp[0] == '*' || exp[0] == '/' || exp[0] == '%' || exp[0] == '+' || exp[l - 1] == '+' || exp[l - 1] == '%' || exp[l - 1] == '/' || exp[l - 1] == '*' || exp[l - 1] == '-') {
document.getElementById("textBox").value = 'NaN';
} else {
exp = document.getElementById("textBox").value;
res = eval(exp);
console.log(res);
document.getElementById("textBox").value = res;
if(res===undefined){
document.getElementById("textBox").value = "";
}
}
}
cal.css:-
*{
box-sizing: border-box;
text-align: center;
padding: 0;
margin: 0;
}
::placeholder {
color: red;
opacity: 1;
}
body {
background: #F6F6F6;
}
.calculator {
max-width: 400px;
margin: 0 auto;
border: 2px solid #111;
border-radius: 5px;
display:flex;
flex-wrap: wrap;
flex: 0 1 60%;
min-width:400px;
color: #F6F6F6;
}
#calc-buttons ,.calc-buttons {
background-color: gray;
border: none;
color: white;
padding-left: 60px;
padding-top: 15px;
text-decoration: none;
display: inline-flex;
font-size: 16px;
margin: 1px;
cursor: pointer;
width:125px;
height: 50px;
border-radius: 6px;
}
.calc-buttons-equal{
background-color:orange;
border: none;
color: white;
padding-left: 190px;
padding-top: 15px;
text-decoration: none;
display: inline-flex;
font-size: 16px;
margin: 1px;
cursor: pointer;
width:388px;
height: 50px;
border-radius: 6px;
}
#textBox1 input {
background: none;
border: none;
box-shadow: none;
padding: 10px;
width: 100%;
border-bottom: 2px solid #111;
color: #333;
text-align: right;
font-size: 40px;
border-radius: 0;
}
I created an api to make a calculator automatically, just put the api inside script tag (<script src="https://calculatorapi.netlify.app/api.js>"). I created this api to help more people build their own web apps. If you want to style my api calculator just do:
<style>
<!--To result input-->
input[type="text"] {
<!--Your style-->
}
<!-- To Calculator buttons e.g: 1,2,3 -->
input[type="buttons"] {
<!-- Your style -->
}
</style>
<!DOCTYPE html>
<html>
<head>
<script>
z="";
fun =""
ans="";
function dis(val)
{
ans = document.getElementById("result").value;
if (ans === "Infinity" ||ans === "-Infinity" || ans === "undefined") {
document.getElementById("result").value = "";
}
if(z&& (val >= 0 || val <= 0)){
z = false;
document.getElementById("result").value="";
document.getElementById("result").value+=val;
}
else{
ans = document.getElementById("result").value+=val;
z = false;
var y = [];
y = document.getElementById("result").value;
p = y.length;
if ((y[p - 2] ==="*" ||y[p - 2] ==="/" ||y[p - 2] ==="%" ||y[p - 2] ==="+" ||y[p - 2] ==="-" ||y[p - 2] ===".") && (val ==="*" ||val ==="/" ||val ==="%" ||val ==="+" ||val ==="-" ||val ===".")) {
document.getElementById("result").value = y.slice(0, p - 2)+y[p-1];
}
}
}
function solve()
{
let i,j;
i= ans;
j=i[i.length-1];
if(i[0]==="*"||i[0]=="/"||i[0]==="%"||i[0]==="+"){
document.getElementById("result").value = undefined;
}
else if(j==="*"||j==="/"||j==="%"||j==="."||j==="+"||j==="-"){
document.getElementById("result").value = undefined;
}
else {
z="";
let x = document.getElementById("result").value;
z = eval(x);
if(z===undefined)
{
document.getElementById("result").value = "";
}
else{
document.getElementById("result").value = z;
}
}
}
function clr()
{
document.getElementById("result").value =""
}
function back()
{
var i = document.getElementById("result").value;
if(i==="undefined"||i==="infinity"||i==="-infinity"){
document.getElementById("result").value ="";
}
else{
document.getElementById("result").value = i.substr(0, i.length - 1);
}
}
</script>
<style>
* {
background-color: black;
height: 100%;
width: 100%;
margin: 0px;
text-align: center;
box-sizing: border-box;
}
.disply{
height: 30%;
width: 100%;
box-sizing: border-box;
}
.functions{
height: 68%;
width: 100%;
box-sizing: border-box;
}
input{
background-color:black;
border:whitesmoke;
color: white;
text-align: center;
font-size: 45px;
cursor: pointer;
height: 20%;
width: 24.2%;
}
button{
background-color:lightslategray;
color: white;
text-align: center;
font-size: 90px;
cursor: pointer;
height: 18%;
width: 24%;
border: none;
border-radius: 50%;
}
button[type=button4]{
width: 48.4%;
padding-right: 24.2%;
border-radius: 40%;
}
button[type=button2]{
background-color: orange;
font-size: 60px;
}
button[type=button1]{
background-color: whitesmoke;
color: black;
font-size: 60px;
}
input[type=text]{
height: 100%;
width: 100%;
background-color:black;
text-align: right;
color: white;
font-size: 100px;
}
::placeholder{
color: bisque;
}
</style>
</head>
<body>
<div class="disply">
<input type="text" id="result" placeholder="0"/>
</div>
<div class="functions">
<button type="button1" value="AC" onclick="clr()">AC</button>
<button type="button1"value="/" onclick="dis('/')">/</button>
<button type="button1"value="%" onclick="dis('%')">%</button>
<button type="button2"value="back" onclick="back()">back</button>
<button type="button3"value="7" onclick="dis('7')">7</button>
<button type="button3"value="8" onclick="dis('8')">8</button>
<button type="button3"value="9" onclick="dis('9')">9</button>
<button type="button2"value="*" onclick="dis('*')">*</button>
<button type="button3"value="4" onclick="dis('4')">4</button>
<button type="button3"value="5" onclick="dis('5')">5</button>
<button type="button3"value="6" onclick="dis('6')">6</button>
<button type="button2"value="-" onclick="dis('-')">-</button>
<button type="button3"value="1" onclick="dis('1')">1</button>
<button type="button3"value="2" onclick="dis('2')">2</button>
<button type="button3"value="3" onclick="dis('3')">3</button>
<button type="button2"value="+" onclick="dis('+')">+</button>
<button type="button4"value="0" onclick="dis('0')">0</button>
<button type="button3"value="." onclick="dis('.')">.</button>
<button type="button2"value="=" onclick="solve()">=</button>
</div>
</body>
</html>