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 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>
Today I started building a dummy client-side web app project in order to improve my basic JavaScript skills. Basically, it's a scientific calculator imitation that runs on line. As you'll see in the code, there are buttons in my HTML file each of which calls to one of the JavaScript functions in my JavaScript file. The calculator doesn't work, I mean, at all, and as I tried debugging, every function in my JavaScript file works by them-self as intended, but seemingly they don't work together.
Here's my code:
var currentMode = 'deg';
var screen = document.getElementById("screen");
var lastChar = screen.value.slice(-1);
/**
* Auxiliary functions
*/
function isNumeric(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
}
function sine(val) {
if (currentMode === 'deg') {
return Math.sin(Math.PI * val / 180);
}
return Math.sin(val);
}
function cos(val) {
if (currentMode === 'deg') {
return Math.cos(Math.PI * val / 180);
}
return Math.cos(val);
}
function tan(val) {
if (currentMode === 'deg') {
return Math.tan(Math.PI * val / 180);
}
return Math.tan(val);
}
function ln(val) {
return Math.log(val);
}
/**
* Calculator functions
*/
function addSpecial(val) {
var nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var operations = ['+', '-', '*', '/', '^'];
if (screen.value === '0') {
if (nums.indexOf(val) >= 0)
screen.value = val;
else if (val === '.' || operations.indexOf(val) >= 0)
screen.value += val;
else
screen.value = '0';
} else if (lastChar === '.' || operations.indexOf(lastChar) >= 0) {
if (val !== '.' && val !== '=' && operations.indexOf(val) < 0)
screen.value += val;
} else {
if (val !== '=')
screen.value += val;
else {
if (lastChar === '.' || operations.indexOf(lastChar) >= 0)
screen.value = 'SYNTAX ERROR!';
else if (screen.value.split('(') !== screen.value.split(')'))
screen.value = 'ERROR! Open or close parantheses!';
else {
try {
screen.value = eval(screen.value);
} catch(err) {
screen.value = err.message;
}
}
}
}
}
function setAngleMode(newMode) {
if (newMode === 'rad') {
if (currentMode === 'deg') {
currentMode = 'rad';
screen.value *= Math.PI / 180;
}
} else {
if (currentMode === 'rad') {
currentMode = 'deg';
screen.value *= 180 / Math.PI;
}
}
}
function addSymbol(val) {
switch (val) {
case 'pi':
screen.value = Math.PI;
break;
case 'e':
screen.value = Math.E;
break;
case 'phi':
screen.value = 1.61803398875;
break;
case 'gamma':
screen.value = 0.5772156649;
}
}
function clearScreen() {
screen.value = '';
}
function clearLast() {
screen.value.slice(0, -1);
}
function inverseVal() {
var len = screen.value.length;
var subs;
for (var i = 0; i < len; ++i) {
for (var j = len; j > i; --j) {
subs = screen.value.slice(i, j);
if (isNumeric(subs)) {
screen.value = 1 / parseFloat(subs);
break;
}
}
}
}
function addSquare() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^2';
}
}
function addPower() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^';
}
}
function addSquareroot() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^(1/2)';
}
}
function addRoot() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^(1/';
}
}
function addExp() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'Math.E^';
}
}
function addSin() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'sine(';
}
}
function addCos() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'cos(';
}
}
function addTan() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'tan(';
}
}
function addLn() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'ln(';
}
}
h5 {
text-align: right;
color: #333333;
font-family: Arial;
font-size: 12px;
font-weight: bold;
margin: 3px;
}
input[type=text] {
text-align: right;
height: 50px;
width: 176px;
padding: 6px;
border: 10px groove #888888;
background-color: #E5DFA0;
font-family: Luicida, monospace;
}
.scientific {
position: relative;
top:0px;
left: 33px;
}
.scientific input[type=button] {
width: 28px;
height: 28px;
background-color: #444444;
color: #BBBBBB;
font-family: Verdana;
font-size: 8px;
font-weight: bold;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.scientific input[type=button].cardinal {
width: 28px;
height: 28px;
background-color: red;
color: white;
font-family: Verdana;
font-size: 8px;
font-weight: bold;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.scientific input[type=image] {
width: 24px;
height: 24px;
background-color: #444444;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.simple input[type=button] {
width: 32px;
height: 32px;
background-color: #EEEEEE;
color: #222222;
font-family: Verdana;
font-size: 11px;
}
.simple input[type=button].roman {
font-family: "Times New Roman", serif;
font-size: 13px;
}
#calc-contain {
width: 180px;
margin: 0px auto;
}
<html>
<head>
<title>::Scientific Calculator::</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<script type="text/javascript" src="engine.js"></script>
</head><body>
<div id="calc-contain">
<img src="EnData.png" alt="EnData" width="180px" />
<h5>SCIENTIFIC CALCULATOR</h5>
<form id="calculator">
<input type="text" id="screen" value="0" readonly />
<div class="scientific">
<div class="line">
<input type="button" value="RAD" onclick="setAngleMode('rad')" />
<input type="button" value="DEG" onclick="setAngleMode('deg')" />
<input type="button" class="cardinal" value="C" onclick="clearScreen()" />
<input type="button" class="cardinal" value="CE" onclick="clearLast()" />
</div><div class="line">
<input type="button" value="sin" onclick="addSin()" />
<input type="button" value="cos" onclick="addCos()" />
<input type="button" value="tan" onclick="addTan()" />
<input type="button" value="ln" onclick="addLn()" />
</div><div class="line">
<input type="image" src="sqr.png" alt="square" onclick="addSquare()" />
<input type="image" src="nthp.png" alt="nth power" onclick="addPower()" />
<input type="image" src="sqrt.png" alt="square root" onclick="addSquareroot()" />
<input type="image" src="nthr.png" alt="nth root" onclick="addRoot()" />
</div><div class="line">
<input type="button" value="1/x" onclick="inverseVal()" />
<input type="button" value="(" onclick="addSpecial('(')" />
<input type="button" value=")" onclick="addSpecial(')')" />
<input type="button" value="exp" onclick="addExp()" />
</div>
</div>
<div class="simple">
<div class="line">
<input type="button" class="roman" value="π" onclick="addSymbol('pi')" />
<input type="button" value="7" onclick="addSpecial('7')" />
<input type="button" value="8" onclick="addSpecial('8')" />
<input type="button" value="9" onclick="addSpecial('9')" />
<input type="button" value=":" onclick="addSpecial('/')" />
</div><div class="line">
<input type="button" class="roman" value="e" onclick="addSymbol('e')" />
<input type="button" value="4" onclick="addSpecial('4')" />
<input type="button" value="5" onclick="addSpecial('5')" />
<input type="button" value="6" onclick="addSpecial('6')" />
<input type="button" value="x" onclick="addSpecial('*')" />
</div><div class="line">
<input type="button" class="roman" value="φ" onclick="addSymbol('phi')" />
<input type="button" value="1" onclick="addSpecial('1')" />
<input type="button" value="2" onclick="addSpecial('2')" />
<input type="button" value="3" onclick="addSpecial('3')" />
<input type="button" value="-" onclick="addSpecial('-')" />
</div><div class="line">
<input type="button" class="roman" value="γ" onclick="addSymbol('gamma')" />
<input type="button" value="0" onclick="addSpecial('0')" />
<input type="button" value="." onclick="addSpecial('.')" />
<input type="button" value="=" onclick="addSpecial('=')" />
<input type="button" value="+" onclick="addSpecial('+')" />
</div>
</div>
</form>
</div>
</body>
</html>
Any help is appreciated.
I am able to get some functionality, (with some parenthesis errors). If it's not working AT ALL, I suspect you are loading the javascript before the DOM is ready which will cause errors with you getElementById. Try either loading in a window.onload handler or put the script before the closing body tag.
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>
In my PhoneGap Eclipse project I am using jQuery for visual effects by referencing jQuery libraries:
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript"
src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.js"></script>
and I am also making remote domain requests in order to display some information from the remote server.
1: When I make requests to multiple servers, I get an error saying:
DroidGap: TIMEOUT ERROR! - calling webViewClient
I read that I must alter my Phonegaps whitelist by doing:
<phonegap>
<access origin="\*\" />
</phonegap>
Source: GitHub call-back
But I get some error, so I have decided to approach same results from the different ways:
2: <script type="text/javascript" src="file:///android_asset/js/jquery.js"></script>
<script type="text/javascript" src="../js/jquery.js"></script>
Why? - because i would like to avoid getting errors with multiple-domain requests
In these cases I get an error
SyntaxError: Parse error at file:///... in logcat
I have no idea why this is happening, because the specified file location supposed to be right in both cases.
So my questions are:
Why I cannot include .js file in this way?
Which solution I should continue trying to approach (1 or 2)?
<html>
<head>
<title></title>
<script src="phonegap-1.3.0.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.0.css" />
<script type="text/javascript" src="jquery.mobile-1.0.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<!--
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="lib/touch/resources/css/sencha-touch.css" type="text/css">
<script type="text/javascript" src="lib/touch/sencha-touch.js"></script>
<!-- <script type="text/javascript" src="lib/touch/index.js"></script> -->
<script>
var alreadyrunflag = 0 //flag to indicate whether target function has already been run
var url = "http://www.norwegian.no/";
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var year = currentTime.getFullYear();
//on page loaded
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", function() {
//alreadyrunflag = 1;
initGet(url);
}, false)
else if (document.all && !window.opera) {
//page load error?
}
function applyChangeEvent() {
//on selection changed
var selectDepart = document.getElementById("depart");
var selectArrive = document.getElementById("arrive");
selectDepart.onchange = function() { //run some code when "onchange" event fires
if (document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value != ""
&& document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value != "") {
for ( var monthsCount = 1; monthsCount < 13; monthsCount++) {
//alert(monthsCount);
get("http://www.norwegian.no/fly/lavpris/", monthsCount);
}
}
}
selectArrive.onchange = function() { //run some code when "onchange" event fires
if (document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value != ""
&& document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value != "") {
for ( var monthsCount = 1; monthsCount < 13; monthsCount++) {
//alert(monthsCount);
get("http://www.norwegian.no/fly/lavpris/", monthsCount);
}
}
}
}
function initGet(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
//request.responseText
getObjs(request.responseText);
}
}
}
request.send();
}
function get(url, month) {
//alert(month);
url += "?D_City="
+ document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value;
url += "&A_City="
+ document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value;
url += "&TripType=1";
url += "&D_Day=1";
url += "&D_Month=" + getMonth(month);
/* url += "&R_Day=1";
url += "&R_Month=201201"; */
url += "&AdultCount=1";
url += "&ChildCount=0";
url += "&InfantCount=0";
//alert(url);
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
//request.responseText
parse(request.responseText, month);
}
}
}
request.send();
}
function getMonth(month) {
//alert(month.toString.length + " | " + month);
if (month.toString().length == 1) {
var tempMonth = "0" + month.toString();
//alert(tempMonth);
return year.toString() + tempMonth;
} else
return year.toString() + month;
}
function getSimpleMonth() {
return month;
}
function getObjs(mainPageHtml) {
var mainDoc = (new DOMParser()).parseFromString(mainPageHtml,
"application/xhtml+xml");
var select = mainDoc.getElementsByTagName("select")[1];
var options = select.getElementsByTagName("option");
var citiesArray = [];
for ( var i = 0; i < options.length; i++) {
cityObj = new Object();
cityObj.name = options[i].text;
cityObj.value = options[i].value;
citiesArray.push(cityObj);
}
for ( var city = 0; city < citiesArray.length; city++) {
document.getElementById("depart").innerHTML += "<option value='"+citiesArray[city].value+"'>"
+ citiesArray[city].name + "</option>";
document.getElementById("arrive").innerHTML += "<option value='"+citiesArray[city].value+"'>"
+ citiesArray[city].name + "</option>";
}
applyChangeEvent();
}
function parse(html, id) {
var pricesArray = [];
//alert(id);
var resultDoc = (new DOMParser()).parseFromString(html,
"application/xhtml+xml");
var divs = resultDoc.getElementsByTagName("table");
for ( var div = 0; div < divs.length; div++) {
if (divs[div].className == "fareCalendarTable") {
//alert("found!");
// TODO: find out how many to open!!
document.getElementById(id).style.display = "block";
document.getElementById("nav_").style.display = "block";
var table = resultDoc.getElementsByTagName("table")[div];
var divs = table.getElementsByTagName("div");
//var tbodyTrs = tbody.getElementsByTagName("tr");
//alert(document.getElementById("month-one").innerHTML);
for ( var price = 0; price < divs.length; price++) {
if (divs[price].title != "") {
/* document.getElementById("month-one-results").innerHTML += divs[price].id
.replace("OutboundFareCal", "")
+ " : " + divs[price].title + "<br>"; */
priceObj = new Object();
priceObj.date = divs[price].id.replace(
"OutboundFareCal", "");
priceObj.price = divs[price].title.replace(" NOK", "");
priceObj.price.replace(/\s/g, '');
pricesArray.push(priceObj);
}
}
/* pricesArray.sort(function sortNumber(a, b) {
return parseInt(b) - parseInt(a);
}); */
for ( var priceUnit = 0; priceUnit < pricesArray.length; priceUnit++) {
document.getElementById("month-results-" + id).innerHTML += "<table><tr><td>"
+ pricesArray[priceUnit].date
+ "</td><td>"
+ pricesArray[priceUnit].price
+ "</td></tr></table>";
}
}
document.getElementById("depart").disabled = "disabled";
document.getElementById("arrive").disabled = "disabled";
}
// document.getElementById("results").innerHTML = bodybox.item(0).innerHTML;
//holy grail!
var month = document.getElementById("month-" + id);
var spans = month.getElementsByTagName("span");
for ( var span = 0; span < spans.length; span++) {
if (spans[span].className == "ui-btn-text") {
spans[span].innerHTML += "<p>" + getCheapest(pricesArray)
+ "</p>";
}
}
}
function getCheapest(pricesArray) {
pricesArray.sort(sort);
return pricesArray[1].price;
}
function sort(a, b) {
if (a.price < b.price)
return -1;
if (a.price > b.price)
return 1;
return 0;
}
function restart() {
window.location.reload();
return false;
document.getElementById("depart").removeAttribute("disabled");
document.getElementById("arrive").removeAttribute("disabled");
}
</script>
<style>
body {
display: block;
padding: 20px;
color: #3D3C2F;
font-family: Arial, Sans-Serif, Helvetica;
font-size: 12px;
font-weight: normal;
}
div#content {
margin-left: auto;
margin-right: auto;
background: #fff;
height: 100%;
-webkit-border-bottom-left-radius: 8px;
-webkit-border-bottom-right-radius: 8px;
display: block;
color: #3D3C2F;
font-family: Arial, Sans-Serif, Helvetica;
font-size: 12px;
font-weight: normal;
background-image:
url(http://www.norwegian.no/Global/backgrounds/background_no.gif);
background-repeat: repeat-x;
background-repeat-x: repeat;
background-repeat-y: no-repeat;
background-position-x: 0%;
background-position-y: 0%;
width: 100%;
padding-top: 20px;
padding-bottom: 30px;
}
div#navigation {
margin-left: auto;
margin-right: auto;
padding: 20px;
position: block;
width: 80%;
background: #CCCC00;
-webkit-border-radius: 8px;
}
select {
position: block;
width: 100%;
text-color: #000;
overflow: hidden;
}
</style>
</head>
<body>
<div id="nav_" data-role="header" data-position="inline" data-theme="e"
style="display: none;">
<a href="#" data-icon="back" data-theme="c"
onClick="window.location.reload();return false;">Start</a>
<h1>Ticket Prices</h1>
</div>
<div id="content">
<div id="navigation">
Fra/From: <select id="depart">
</select> Til/To: <select id="arrive">
</select>
</div>
<div data-role="collapsible" id="1"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-1">January</h3>
<p id="month-results-1"></p>
</div>
<div data-role="collapsible" id="2"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-2">February</h3>
<p id="month-results-2"></p>
</div>
<div data-role="collapsible" id="3"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-3">March</h3>
<p id="month-results-3"></p>
</div>
<div data-role="collapsible" id="4"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-4">April</h3>
<p id="month-results-4"></p>
</div>
<div data-role="collapsible" id="5"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-5">May</h3>
<p id="month-results-5"></p>
</div>
<div data-role="collapsible" id="6"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-6">June</h3>
<p id="month-results-6"></p>
</div>
<div data-role="collapsible" id="7"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-7">July</h3>
<p id="month-results-7"></p>
</div>
<div data-role="collapsible" id="8"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-8">August</h3>
<p id="month-results-8"></p>
</div>
<div data-role="collapsible" id="9"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-9">September</h3>
<p id="month-results-9"></p>
</div>
<div data-role="collapsible" id="10"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-10">October</h3>
<p id="month-results-10"></p>
</div>
<div data-role="collapsible" id="11"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-11">November</h3>
<p id="month-results-11"></p>
</div>
<div data-role="collapsible" id="12"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-12">December</h3>
<p id="month-results-12"></p>
</div>
</div>
<!-- <div id="results"></div> -->
</body>
</html>
If your directory structure is assets/www/js/jquery.js use :
<script type="text/javascript" src="js/jquery.js"></script>