JavaScript functions working by themselves but not working together - javascript

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.

Related

How to combine input values together

I am trying to combine Input values. Below is my working code, any help is appreciated.
Here is my code:
getCodeBoxElement(index) {
return document.getElementById("codeBox" + index);
}
onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
console.log((<HTMLInputElement>this.getCodeBoxElement(index)).value);
if ((<HTMLInputElement>this.getCodeBoxElement(index)).value.length === 1) {
if (index !== 6) {
this.getCodeBoxElement(index + 1).focus();
} else {
this.getCodeBoxElement(index).blur();
// Submit code
// for(var i=0; i<6; i++){
// this.verificationCode = (<HTMLInputElement>this.getCodeBoxElement(i)).toString;
// console.log(this.verificationCode);
// }
console.log("submit code ");
}
}
if (eventCode === 8 && index !== 1) {
this.getCodeBoxElement(index - 1).focus();
}
}
onFocusEvent(index) {
for (var item = 1; item < index; item++) {
const currentElement = this.getCodeBoxElement(item);
if (!(<HTMLInputElement>currentElement).value) {
currentElement.focus();
break;
}
}
}
/* Body Styling only end */
section {
display: flex;
/* align-items: center;
width: 100vw;
height: 100vh; */
text-align: center;
}
section form {
display: flex;
align-items: center;
width: auto;
margin-left: 12px;
/* margin: 0 auto; */
}
section form input {
width: 40px;
height: 40px;
text-align: center;
margin-left: -10px;
border: none;
border-radius: 10px;
}
section form input:last-child {
margin-right: 0;
}
section form input::-webkit-inner-spin-button,
section form input::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
section form input:focus,
section form input.focus {
border-color: green;
outline: none;
box-shadow: none;
}
<section>
<form style="margin-top: 10px;">
<input id="codeBox1" type="text" maxlength="1" (keyup)="onKeyUpEvent(1, $event)"
(focus)="onFocusEvent(1)" autocomplete="off">
<input id="codeBox2" type="text" maxlength="1" (keyup)="onKeyUpEvent(2, $event)"
(focus)="onFocusEvent(2)" autocomplete="off">
<input id="codeBox3" type="text" maxlength="1" (keyup)="onKeyUpEvent(3, $event)"
(focus)="onFocusEvent(3)" autocomplete="off">
<input id="codeBox4" type="text" maxlength="1" (keyup)="onKeyUpEvent(4, $event)"
(focus)="onFocusEvent(4)" autocomplete="off">
<input id="codeBox5" type="text" maxlength="1" (keyup)="onKeyUpEvent(5, $event)"
(focus)="onFocusEvent(5)" autocomplete="off">
<input id="codeBox6" type="text" maxlength="1" (keyup)="onKeyUpEvent(6, $event)"
(focus)="onFocusEvent(6)" autocomplete="off">
<!-- <input id="codeBox5" type="text" maxlength="1" (keyup)="onKeyUpEvent(5, $event)"
(focus)="onFocusEvent(5)" autocomplete="off">
<input id="codeBox6" type="text" maxlength="1" (keyup)="onKeyUpEvent(6, $event)"
(focus)="onFocusEvent(6)" autocomplete="off"> -->
</form>
</section>
Inputs return the value of the input as a string by default... So concatenating the values will combine them by default... If you want to add them as you would numbers, you would need to parse the value as an integer... Otherwise you can simply combine their values by using the plus symbol + => input.value + input2.value. Even the input type number value will return a string so by concatenating the values together you will be combining their values into one string, this would include numbers with typeof = string.
See my example inputs and their outputs for reference...
EDIT: For your issue, you can create an array to hold the value of each input through the iteration in your function... Once you have reached the threshold conditional, join the values of your array.
// create an array to hold your values
let code = new Array;
function onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
if (getCodeBoxElement(index).value.length === 1) {
// save the value within your array with each selection
code[index] = getCodeBoxElement(index).value
if (index !== 4) {
getCodeBoxElement(index+ 1).focus();
} else {
getCodeBoxElement(index).blur();
// Submit code
// join the array values into a string using .join('');
let codeString = code.join('')
console.log(codeString)
}
}
if (eventCode === 8 && index !== 1) {
getCodeBoxElement(index - 1).focus();
}
}
function getCodeBoxElement(index) {
return document.getElementById('codeBox' + index);
}
let code = new Array;
function onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
if (getCodeBoxElement(index).value.length === 1) {
//code[index] = getCodeBoxElement(index).value also works
code.push(getCodeBoxElement(index).value)
if (index !== 4) {
getCodeBoxElement(index + 1).focus();
} else {
getCodeBoxElement(index).blur();
// Submit code
let codeString = code.join('');
let display = document.getElementById('display')
display.style.color = 'darkgreen';
display.textContent = `You have entered: ${codeString}`;
}
}
if (eventCode === 8 && index !== 1) {
getCodeBoxElement(index - 1).focus();
}
}
function onFocusEvent(index) {
for (item = 1; item < index; item++) {
const currentElement = getCodeBoxElement(item);
if (!currentElement.value) {
currentElement.focus();
break;
}
}
}
// Body Styling only Begin ==============
body {
text-align: center;
background-color: lightcyan;
font-family: 'POPPINS', Open-Sans;
background: linear-gradient(to right, #4568dc, #b06ab3);
}
::selection {
color: #8e44ad;
}
// Body Styling only End ================
// Container-fluid Styling only Begin ===
.container-fluid {
.row {
align-items: center;
width: 100vw;
height: 100vh;
}
}
// Container-fluid Styling only End =====
// =====
// Passcode-wrapper Styling only Begin ==
.passcode-wrapper {
display: flex;
justify-content: space-between;
align-items: center;
width: auto;
margin: 0 auto;
input {
width: 50px;
height: 50px;
padding: 0;
margin-right: 5px;
text-align: center;
border: 1px solid gray;
border-radius: 5px;
&:last-child {
margin-right: 0;
}
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
&:focus,
&.focus {
border-color: green;
outline: none;
box-shadow: none;
}
}
}
// Passcode-wrapper Styling only End ====
<section class="container-fluid">
<div class="row">
<div class="col-md-8 offset-md-2">
<form class="text-center">
<div class="form-group">
<label for="password" class="text-white">Enter 4 Digit Password</label>
<div class="passcode-wrapper">
<input id="codeBox1" type="number" maxlength="1" onkeyup="onKeyUpEvent(1, event)" onfocus="onFocusEvent(1)">
<input id="codeBox2" type="number" maxlength="1" onkeyup="onKeyUpEvent(2, event)" onfocus="onFocusEvent(2)">
<input id="codeBox3" type="number" maxlength="1" onkeyup="onKeyUpEvent(3, event)" onfocus="onFocusEvent(3)">
<input id="codeBox4" type="number" maxlength="1" onkeyup="onKeyUpEvent(4, event)" onfocus="onFocusEvent(4)">
</div>
</div>
</form>
</div>
</div>
</section>
<div id="display"></div>
I just did it like this when I did something like this.
document.onkeyup = function() {
ch = document.getElementsByClassName("ch");
x = ch.length;
out = "";
for (y=0;x>y;y++) {
out += ch[y].value;
}
document.getElementById("final").innerHTML = out;
}
<input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'>
<span id="final" style="color: green;"></span>

How do I create a button with new text on click?

Incredibly novice coder here. Like, complete beginner aside from Tumblr and Neopets teaching me how to read and do basic tinkering.
I've maybe bitten off more than I can chew on this project, anybody willing to help?
Needing 5 buttons in a single column where "on click" the text changes. I got it to work for 1, but adding 5 on the same page all the buttons go random and I think they need individual IDs, but I have no idea how to do that.
<!DOCTYPE html>
<html>
<head>
<style>
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
margin: 4px 2px;
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
</style>
</head>
<body>
<center>
<input type="button" id= "bf3" class="button" value="BF₃" onclick="return change(this);" />
<script type="text/javascript">
function change( bf3 )
{
if (bf3.value === "BF₃" )
bf3.value = "boron trifluoride";
else
bf3.value = "BF₃";
}
</script>
</center>
</body>
</html>
<body>
<center>
<input type="button" id= "sf6" class="button" value="SF₆" onclick="return change(this);" />
<script type="text/javascript">
function change( sf6 )
{
if ( sf6.value === "SF₆" )
sf6.value = "sulfur hexafluoride";
else
sf6.value = "SF₆";
}
</script>
</center>
</body>
</html>
<body>
<center>
<input type="button" id="h2o" class="button" value="H₂O" onclick="return change(this);" />
<script type="text/javascript">
function change( h2o )
{
if ( h2o.value === "H₂O" )
h2o.value = "dihydrogen monoxide (aka water)";
else
h2o.value = "H₂O";
}
</script>
</center>
</body>
<body>
<center>
<input type="button" id="pcl5" class="button" value="PCl₅" onclick="return change(this);" />
<script type="text/javascript">
function change( pcl5 )
{
if ( pcl5.value === "PCl₅" )
pcl5.value = "phosphorus pentachloride";
else
pcl5.value = "PCl₅;
}
</script>
</center>
</body>
</html>
<body>
<center>
<input type="button" class="button" id="n2h4" value="N₂H₄" onclick="return change(this);" />
<script type="text/javascript">
function change( n2h4 )
{
if ( n2h4.value === "N₂H₄" )
n2h4.value = "dinitrogen tetrahydride";
else
n2h4.value = "N₂H₄;
}
</script>
</center>
</body>
</html>
I would do it like this for more maintainability:
var container = document.getElementById('container');
var molecules = [
{ formula: "BF₃", name: "boron trifluoride" },
{ formula: "SF₆", name: "sulfur hexafluoride" },
{ formula: "H₂O", name: "dihydrogen monoxide (aka water)" },
{ formula: "PCl₅", name: "phosphorus pentachloride" },
{ formula: "N₂H₄", name: "dinitrogen tetrahydride" }
];
molecules.forEach(function(m) {
var showName = false;
var btn = document.createElement('input');
btn.type = 'button';
btn.className = 'button';
btn.value = m.formula;
btn.addEventListener('click', function() {
showName = !showName;
btn.value = showName ? m.name : m.formula;
});
container.appendChild(btn);
container.appendChild(document.createElement('br'));
});
#container { text-align: center; }
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
margin: 4px 2px;
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
<div id="container"></div>
You do not need multiple functions to achieve that. Simply check the value of the currently clicked button and set the value accordingly.
Try the following way:
function change(currBtn){
if(currBtn.value == 'BF₃' || currBtn.value == 'boron trifluoride'){
if(currBtn.value == 'BF₃')
currBtn.value = 'boron trifluoride';
else
currBtn.value = 'BF₃';
}
else if(currBtn.value == 'SF₆' || currBtn.value == 'sulfur hexafluoride'){
if(currBtn.value == 'SF₆')
currBtn.value = 'sulfur hexafluoride';
else
currBtn.value = 'SF₆';
}
else if(currBtn.value == 'H₂O' || currBtn.value == 'dihydrogen monoxide (aka water)'){
if(currBtn.value == 'H₂O')
currBtn.value = 'dihydrogen monoxide (aka water)';
else
currBtn.value = 'H₂O';
}
else if(currBtn.value == 'PCl₅' || currBtn.value == 'phosphorus pentachloride'){
if(currBtn.value == 'PCl₅')
currBtn.value = 'phosphorus pentachloride';
else
currBtn.value = 'PCl₅';
}
else if(currBtn.value == 'N₂H₄' || currBtn.value == 'dinitrogen tetrahydride'){
if(currBtn.value == 'N₂H₄')
currBtn.value = 'dinitrogen tetrahydride';
else
currBtn.value = 'N₂H₄'
}
}
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
margin: 4px 2px;
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
<center>
<input type="button" id= "bf3" class="button" value="BF₃" onclick="change(this);" />
</center>
<center>
<input type="button" id= "sf6" class="button" value="SF₆" onclick="change(this);" />
</center>
<center>
<input type="button" id="h2o" class="button" value="H₂O" onclick="change(this);" />
</center>
<center>
<input type="button" id="pcl5" class="button" value="PCl₅" onclick="change(this);" />
</center>
<center>
<input type="button" class="button" id="n2h4" value="N₂H₄" onclick="change(this);" />
</center>
My way...
const buttonList =
[ [ 'BF₃', 'boron trifluoride' ]
, [ 'SF₆', 'sulfur hexafluoride' ]
, [ 'H₂O', 'dihydrogen monoxide (aka water)' ]
, [ 'PCl₅', 'phosphorus pentachloride' ]
, [ 'N₂H₄', 'dinitrogen tetrahydride' ]
];
buttonList.forEach(bt=>
{
let newbt = document.createElement('button')
, timOut = null;
newbt.className = 'button'
newbt.textContent = bt[0]
document.documentElement.appendChild( newbt )
newbt.onclick=()=>{
newbt.textContent = bt[1]
clearTimeout(timOut)
timOut = setTimeout(()=>{ newbt.textContent = bt[0] }, 1500)
}
})
/* or
buttonList.forEach(bt=>
{
let newbt = document.createElement('button')
, LibNum = 0
newbt.className = 'button'
newbt.textContent = bt[0]
newbt.onclick=()=>{ LibNum = ++LibNum %2; newbt.textContent = bt[LibNum] }
document.documentElement.appendChild( newbt )
})
*/
.button {
font-family: 'Quattrocento Sans', sans-serif;
font-size: 18px;
display: block;
margin: .2em auto;
padding: 1em;
color: #08365F;
background-color: #f0c640;
border: none;
cursor: pointer;
text-align: center;
min-width: 5em;
}
Did I still take the time to correct your code to help you?
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<title> sample code </title>
<style>
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px;
display: block; /* must be block to be centered */
font-size: 18px;
margin: 4px auto; /* this one replace <center> tag (obsolete) */
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
</style>
</head>
<body>
<input type="button" id="bf3" class="button" value="BF₃" onclick="xchange(this);" />
<input type="button" id="sf6" class="button" value="SF₆" onclick="xchange(this);" />
<input type="button" id="h2o" class="button" value="H₂O" onclick="xchange(this);" />
<input type="button" id="pcl5" class="button" value="PCl₅" onclick="xchange(this);" />
<input type="button" id="n2h4" class="button" value="N₂H₄" onclick="xchange(this);" />
<script>
function xchange( btn )
{
switch (btn.id) {
case 'bf3': btn.value = (btn.value==='BF₃') ? 'boron trifluoride' : 'BF₃'; break;
case 'sf6': btn.value = (btn.value==='SF₆') ? 'sulfur hexafluoride' : 'SF₆'; break;
case 'h2o': btn.value = (btn.value==='H₂O') ? 'dihydrogen monoxide (aka water)' : 'H₂O'; break;
case 'pcl5': btn.value = (btn.value==='PCl₅') ? 'phosphorus pentachloride' : 'PCl₅'; break;
case 'n2h4': btn.value = (btn.value==='N₂H₄') ? 'dinitrogen tetrahydride' : 'N₂H₄'; break;
} }
</script>
</body>
</html>

Textarea won't display values after hitting Reset

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

Calculator with Javascript

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>

How to apply CSS styling to elements created by jquery's append()?

I am trying to create a dynamic form, and have run into a problem with styling that makes itself quite apparent when you add elements to a form. There is styling added to inputs on load that aren't applied to any created when I add them with jQuery's append() function. The margins are nonexistant on the new input elements, whereas if I add them manually in the beginning on page load the styling is there. Seems to be some browser default styling which I cannot override. How do I fix this? Example code below.
CSS:
#GraphTools
{
border-top: 1px solid #BBBBBB;
height: 24px;
margin: 0 5px 3px;
padding-top: 2px;
}
#GraphSearch
{
float: left;
}
#GraphTools input
{
background-color: rgba(255, 255, 255, 0.4);
border-radius: 3px 3px 3px 3px;
box-shadow: 0 0 2px #444444 inset;
font-size: 14px;
padding: 2px;
}
#GraphTools input[type=button]:active, #GraphTools input[type=submit]:active
{
background-color: rgba(192, 192, 192, 0.4);
}
#GraphSearchFields
{
float: left;
margin-right: 5px;
}
#GraphSearchFields input
{
margin: 0 5px 0 5px;
}
#GraphZoom
{
float: right;
}
HTML:
<div id="GraphTools">
<div id="GraphSearch">
<form id="GraphSearchForm">
<div id="GraphSearchFields">
<input type="text" data-default-value="Sender" id="SenderBox0" class="GraphSearchBox" />
<input type="text" data-default-value="Reciever" id="RecieverBox0" class="GraphSearchBox" />
<input type="text" data-default-value="Sender" id="SenderBox1" class="GraphSearchBox" />
<input type="text" data-default-value="Reciever" id="RecieverBox1" class="GraphSearchBox" />
</div>
<input type="button" id="AddNewHumanSet" value="+" />
<input type="submit" value="Go" />
<input type="button" value="Reset" class="GraphResetButton" />
</form>
</div>
<div id="GraphZoom">
<input type="button" value="-" />
<input type="button" value="+" />
</div>
</div>
Javascript:
$(document).ready(function ()
{
function LoadDefaultSearchBoxValues()
{
$(".GraphSearchBox").each(function (i, e)
{
if ($(this).val() == "")
{
$(this).val($(this).data("default-value"));
}
});
}
LoadDefaultSearchBoxValues();
$(".GraphSearchBox").live("focus", function ()
{
if ($(this).val() == $(this).data("default-value"))
{
$(this).val("");
}
});
$(".GraphSearchBox").live("blur", function ()
{
if ($(this).val() == "")
{
$(this).val($(this).data("default-value"));
}
});
$("#GraphSearchForm").live("submit", function (event)
{
event.preventDefault();
var SenderBoxHasValue = !($("#SenderBox").val() == $("#SenderBox").data("default-value") && $("#SenderBox").val() == "");
var RecieverBoxHasValue = !($("#RecieverBox").val() == $("#RecieverBox").data("default-value") && $("#RecieverBox").val() == "");
if (SenderBoxHasValue && RecieverBoxHasValue)
{
graph.filterEdges(function (edge)
{
return edge.source.data.label.toLowerCase().indexOf($("#SenderBox").val().toLowerCase()) != -1 &&
edge.target.data.label.toLowerCase().indexOf($("#RecieverBox").val().toLowerCase()) != -1;
});
}
else if (SenderBoxHasValue)
{
graph.filterEdges(function (edge)
{
return edge.source.data.label.toLowerCase().indexOf($("#SenderBox").val().toLowerCase()) != -1;
});
}
else if (RecieverBoxHasValue)
{
graph.filterEdges(function (edge)
{
return edge.target.data.label.toLowerCase().indexOf($("#RecieverBox").val().toLowerCase()) != -1;
});
}
});
$(".GraphResetButton").live("click", function ()
{
graph.resetGraph();
});
$("#AddNewHumanSet").live("click", function ()
{
var inputcount = $("#GraphSearchFields").children("input").length / 2;
var mod4 = $("#GraphSearchFields").children("input").length % 4;
if (mod4 == 0)
{
$("#GraphSearchFields").append("<br />");
}
$("#GraphSearchFields").append('<input type="text" data-default-value="Sender" id="SenderBox' + inputcount + '" class="GraphSearchBox" /><input type="text" data-default-value="Reciever" id="RecieverBox' + inputcount + '" class="GraphSearchBox" />');
LoadDefaultSearchBoxValues();
});
});
You need to put a space in between 2 input boxes when you append them.
Take a look at this working demo it is fine now
http://jsfiddle.net/2xfED/1/

Categories

Resources