Code working in JsBin but not any other browsers - javascript

This question asked before and I read all of them, tried to implement the suggestions given but no luck. It's a calculator with basic functionality.
Numbers are not displaying in the screen, operators are not working. Basically, js file is not working.
- Scope issue; Inserted js file in window.onload=function(){}.
- Tried to find bugs but code looks okay.
I linked css and js files as separate, code is working in JsBin but not any browsers.
Any suggestions:
Here are my codes:
<!DOCTYPE html>
<html>
<head>
<title> Basic Calculator </title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="container">
<form name="calculator">
<input type="text" id="display" />
<br>
<input type="button" value=' CLEAR ' class="operator" onclick='clearDisplay("clear")' />
<input type="button" value=' DEL ' class="keys" onclick='backSpace()' />
<input type="button" value=' + ' class="keys" onclick='passToScreen("+")' />
<br />
<input type="button" value=' 9 ' class="keys" onclick='passToScreen("9")' />
<input type="button" value=' 8 ' class="keys" onclick='passToScreen("8")' />
<input type="button" value=' 7 ' class="keys" onclick='passToScreen("7")' />
<input type="button" value=' - ' class="keys" onclick='passToScreen("-")' />
<br />
<input type="button" value=' 6 ' class="keys" onclick='passToScreen("6")' />
<input type="button" value=' 5 ' class="keys" onclick='passToScreen("5")' />
<input type="button" value=' 4 ' class="keys" onclick='passToScreen("4")' />
<input type="button" value=' * ' class="keys" onclick='passToScreen("*")' />
<br />
<input type="button" value=' 3 ' class="keys" onclick='passToScreen("3")' />
<input type="button" value=' 2 ' class="keys" onclick='passToScreen("2")' />
<input type="button" value=' 1 ' class="keys" onclick='passToScreen("1")' />
<input type="button" value=' / ' class="keys" onclick='passToScreen("/")' />
<br />
<input type="button" value=' 0 ' class="keys" onclick='passToScreen("0")' />
<input type="button" value=' . ' class="keys" onclick='passToScreen(".")' />
<input type="button" value=' = ' class="operator" onclick='doMath()' />
<br />
</form>
</div>
</body>
</html>
CSS code:
body {
background-color: lightgrey;
}
#container {
position: relative;
width: 300px;
height: 320px;
border: 2px solid blue;
border-radius: 4px;
background-color: white;
padding: 20px;
margin: 50px auto;
box-shadow: 3px 2px 2px 1px lightblue;
}
input[type=button] {
background: lightgrey;
width: 20%;
font-size: 20px;
font-weight: 900;
font: white;
margin: 2%;
border-radius: 4px;
box-shadow: 0px 0px 2px 1px black;
outline: none;
}
#container .operator {
width: 45%;
}
input[type=text] {
position: relative;
display: block;
height: 40px;
width: 93%;
border: 2px solid black;
border-radius: 5px;
box-shadow: 0px 0px 1px black;
margin: 5px 5px -2px 5px;
text-align: right;
outline: none;
font-size: 25px;
font-weight: bold;
padding-right: 5px;
}
JS file:
window.onload = function() {
var screen = document.getElementById("display");
function passToScreen(x) {
screen.value += x;
}
function clearDisplay() {
screen.value = "";
}
function doMath() {
var y = screen.value;
y = eval(y);
screen.value = y;
}
function backSpace() {
var elem = screen.value;
var newElem = elem.slice(0, elem.length - 1);
screen.value = newElem;
}
}
Thank you for your time.
Cheers #Tiyor.

When you load the js via window.onload your functions are only available within the scope of that closure.
Attempting to refer to them in the onclick handler will fail because it needs them to be globally available.
You need to add the functions to the window object like this
window.onload=function(){
var screen = document.getElementById("display");
window.passToScreen = function (x) {
screen.value += x;
}
window.clearDisplay = function () {
screen.value = "";
}
window.doMath = function() {
var y = screen.value;
y = eval(y);
screen.value = y;
}
window.backSpace = function() {
var elem = screen.value;
var newElem = elem.slice(0, elem.length - 1);
screen.value = newElem;
}
}
https://jsbin.com/dugiyuwuco/1/edit?html,css,js,output

Related

Javascript Calculator- Math Sign & Infinity

I'm trying to create a calculator with basic operators. So far I have a good deal of it running but I'm attempting to write a button to change the math sign from positive and negative and back. I 'm also unsure how to make dividing by zero show Error instead of infinity. I'm aware the math sign in my code currently does nothing, I 'm not sure how to go about it.
function clearDisplay() {
var display = document.getElementById('display');
display.value = '0';
storedNum = '0';
calculationFinished = true;
operation = operations.none;
}
function clearPreviousResult() {
var display = document.getElementById('display');
if (calculationFinished) {
display.value = '0';
calculationFinished = false;
}
}
function numInput(digit) {
var display = document.getElementById('display');
clearPreviousResult(); // Get rid of a 0 if it's the only thing in there.
// This particular way of doing it lets you enter a 0 and have it show up, as well as leaving a 0 for the decimal point to snuggle up to
if (display.value === '0') display.value = '';
display.value += digit;
}
function insertDecimal() {
var display = document.getElementById('display');
clearPreviousResult();
if (display.value.indexOf('.') === -1) display.value += '.';
}
operations = {
// no-op. Takes the right side, and just returns it. Since the right side is the display value, and calculate() sets display.value, this effectively makes calculate() say "display.value = +display.value".
none: function(left, right) { return right; }, // Math ops.
add: function(left, right) { return left + right; },
subtract: function(left, right) { return left - right; },
multiply: function(left, right) { return left * right; },
divide: function(left, right) { return left / right; },
};
function setOperation(command) {
var display = document.getElementById('display');
calculate();
storedNum = display.value;
if (operations.hasOwnProperty(command))
operation = operations[command];
}
function calculate() {
var display = document.getElementById('display');
display.value = operation(+storedNum, +display.value);
calculationFinished = true;
operation = operations.none;
}
if ('addEventListener' in window)
window.addEventListener('load', clearDisplay);
else
window.attachEvent('onload', clearDisplay);
body {
background-color: lightgrey;
}
#container {
position: relative;
width: 300px;
height: 320px;
border: 2px solid grey;
border-radius: 4px;
background-color: navy;
padding: 20px;
margin: 50px auto;
box-shadow: 3px 2px 2px 1px black;
}
input[type=button] {
background: lightgrey;
width: 20%;
font-size: 20px;
font-weight: 900;
font: white;
margin: 2%;
border-radius: 4px;
box-shadow: 0px 0px 2px 1px black;
outline: none;
}
#container .operator {
width: 45%;
}
input[type=text] {
position: relative;
display: block;
height: 40px;
width: 93%;
border: 2px solid black;
border-radius: 5px;
box-shadow: 0px 0px 1px black;
margin: 5px 5px -2px 5px;
text-align: right;
outline: none;
font-size: 25px;
font-weight: bold;
padding-right: 5px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script>
</script>
</head>
<body>
<form class="calcForm" name="calculator">
<input type="text" class="calcDisplay" id="display" />
<div class="calcRow">
<input type="button"
class="calcButton"
value="7"
onclick="numInput('7')" />
<input type="button"
class="calcButton"
value="8"
onclick="numInput('8')" />
<input type="button"
class="calcButton"
value="9"
onclick="numInput('9')" />
<input type="button"
class="calcButton"
value="+"
onclick="setOperation('add')" />
</div>
<div class="calcRow">
<input type="button"
class="calcButton"
value="4"
onclick="numInput('4')" />
<input type="button"
class="calcButton"
value="5"
onclick="numInput('5')" />
<input type="button"
class="calcButton"
value="6"
onclick="numInput('6')" />
<input type="button"
class="calcButton"
value="-"
onclick="setOperation('subtract')" />
</div>
<div class="calcRow">
<input type="button"
class="calcButton"
value="1"
onclick="numInput('1')" />
<input type="button"
class="calcButton"
value="2"
onclick="numInput('2')" />
<input type="button"
class="calcButton"
value="3"
onclick="numInput('3')" />
<input type="button"
class="calcButton"
value="x"
onclick="setOperation('multiply')" />
</div>
<div class="calcRow">
<input type="button"
class="calcButton"
value="0"
onclick="numInput('0')" />
<input type="button"
class="calcButton"
value="."
onclick="insertDecimal('.')" />
<input type="button"
class="calcButton"
value="+/-"
onclick="setOperation()" />
<input type="button"
class="calcButton"
value="/"
onclick="setOperation('divide')" />
</div>
<div class="calcRow">
<input type="button"
class="calcButton"
value="C"
onclick="clearDisplay()" />
<input type="button"
class="calcButton"
value="="
onclick="calculate()" />
</div>
</form>
</body>
</html>
In math, to flip a number's sign, you can multiply (or divide) it by -1, so:
/* you shouldn't redeclare "display" in the body of
every function, just declare the one and reuse it */
var display = document.getElementById('display');
function flipSignOperation() {
display.value *= -1;
}
To prevent a division by 0, you can change the body of operations["divide"] to this:
return right !== 0 ? left / right : "Error!";
I am using JavaScript's Conditional Ternary Operator. If you wanted to do it in a simpler way (but the first one's 1 line while this is 5):
if(right !== 0) {
return left / right;
} else {
return "Error!";
}
P.S it's a wonder your question hasn't been downvoted to the depths of Tartarus by now.

Javascript calculator. How to stop multiple operands?

I have been working on a calculator as a learning project for myself. It is working fine except I cannot figure out how to stop people from adding app breaking inputs such as 1++-*/4. I have tried various things like splitting my current display into an array and comparing it to another array with all the operators. I have also tried if(output.includes(input){ blah blah }.
I tried adding an extra else if to the getbuttonpress which went something like this else if(input == "*" || input == "+" || input == "/" || input = "-"){do something}
It didn't really work out for me.
Could someone please explain some different methods that I could use to resolve the issue?
Here is my code:
var resultDisplayed = false;
function getButtonPress() {
var input = this.value;
if (input == "=") {
console.log("bang");
getResult();
} else if (resultDisplayed && input < 10) {
document.getElementById("output").innerHTML = input;
resultDisplayed = false;
} else {
document.getElementById("output").innerHTML += input;
console.log(input);
resultDisplayed = false;
}
}
window.onload = function() {
[].slice.call(document.getElementsByClassName("button")).forEach(function(e) {
e.addEventListener('click', getButtonPress);
});
};
function getResult() {
var result = document.getElementById("output").innerHTML;
var resultCalculated = eval(result);
console.log(resultCalculated);
document.getElementById("output").innerHTML = resultCalculated;
resultDisplayed = true;
}
/* Fonts from Google Fonts - more at https://fonts.google.com */
#import url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');
#import url('https://fonts.googleapis.com/css?family=Merriweather:400,700');
body {
background-color: white;
font-family: "Open Sans", sans-serif;
font-size: 18px;
color: #444;
text-align: center;
}
h1 {
font-family: "Merriweather", serif;
font-size: 32px;
}
#calculator {
width: 250px;
height: 400px;
position: absolute;
background-color: grey;
padding: 15px;
box-shadow: 5px 5px 5px 5px;
margin: auto;
}
.button {
width: 19%;
height: 70px;
box-shadow: 1px 1px 1px 1px;
border: 1px solid black;
display: inline-block;
margin: 5px;
}
.buttonContainer {
width: 95%;
margin: auto;
margin-top: 10px;
}
#screen {
width: 90%;
height: 15%;
background-color: green;
margin: auto;
color: white;
text-align: right;
overflow: hidden;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Calculator</h1>
<div id="calculator">
<div id="screen">
<h1 id="output">0</h1>
</div>
<div class="buttonContainer">
<button class="button" value="7">
<h1 class = "number">7</h1>
</button>
<button class="button" value="8">
<h1 class = "number">8</h1>
</button>
<button class="button" value="9">
<h1 class = "number">9</h1>
</button>
<button class="button" value="+">
<h1 class = "number">+</h1>
</button>
<button class="button" value="4">
<h1 class = "number">4</h1>
</button>
<button class="button" value="5">
<h1 class = "number">5</h1>
</button>
<button class="button" value="6">
<h1 class = "number">6</h1>
</button>
<button class="button" value="-">
<h1 class = "operator">-</h1>
</button>
<button class="button" value="1">
<h1 class = "number">1</h1>
</button>
<button class="button" value="2">
<h1 class = "number">2</h1>
</button>
<button class="button" value="3">
<h1 class = "number">3</h1>
</button>
<button class="button" value="*">
<h1 class = "operator">*</h1>
</button>
<button class="button" value=".">
<h1 class = "operator">.</h1>
</button>
<button class="button" value="0">
<h1 class = "number">0</h1>
</button>
<button class="button" value="=">
<h1 class = "operator">=</h1>
</button>
<button class="button" value="/">
<h1 class = "operator">/</h1>
</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Add the below code to your getButtonPress function
It will check whether both the current input and previous entry are operators.
If yes, it will replace the previous operator with new one
var element=document.getElementById("output");
if (/[+-\/*]/.test(this.value) && /[+-\/*]$/.test(element.innerHTML)) {
element.innerHTML = element.innerHTML.replace(element.innerHTML[element.innerHTML.length - 1], '');
}
var resultDisplayed = false;
function getButtonPress() {
var input;
var element=document.getElementById("output");
if (/[+-\/*]/.test(this.value) && /[+-\/*]$/.test(element.innerHTML)) {
element.innerHTML = element.innerHTML.replace(element.innerHTML[element.innerHTML.length - 1], '');
}
input = this.value;
if (input == "=") {
console.log("bang");
getResult();
} else if (resultDisplayed && input < 10) {
document.getElementById("output").innerHTML = input;
resultDisplayed = false;
} else {
document.getElementById("output").innerHTML += input;
resultDisplayed = false;
}
}
window.onload = function() {
[].slice.call(document.getElementsByClassName("button")).forEach(function(e) {
e.addEventListener('click', getButtonPress);
});
};
function getResult() {
var result = document.getElementById("output").innerHTML;
var resultCalculated = eval(result);
console.log(resultCalculated);
document.getElementById("output").innerHTML = resultCalculated;
resultDisplayed = true;
}
/* Fonts from Google Fonts - more at https://fonts.google.com */
#import url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');
#import url('https://fonts.googleapis.com/css?family=Merriweather:400,700');
body {
background-color: white;
font-family: "Open Sans", sans-serif;
font-size: 18px;
color: #444;
text-align: center;
}
h1 {
font-family: "Merriweather", serif;
font-size: 32px;
}
#calculator {
width: 250px;
height: 400px;
position: absolute;
background-color: grey;
padding: 15px;
box-shadow: 5px 5px 5px 5px;
margin: auto;
}
.button {
width: 19%;
height: 70px;
box-shadow: 1px 1px 1px 1px;
border: 1px solid black;
display: inline-block;
margin: 5px;
}
.buttonContainer {
width: 95%;
margin: auto;
margin-top: 10px;
}
#screen {
width: 90%;
height: 15%;
background-color: green;
margin: auto;
color: white;
text-align: right;
overflow: hidden;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Calculator</h1>
<div id="calculator">
<div id="screen">
<h1 id="output">0</h1>
</div>
<div class="buttonContainer">
<button class="button" value="7">
<h1 class = "number">7</h1>
</button>
<button class="button" value="8">
<h1 class = "number">8</h1>
</button>
<button class="button" value="9">
<h1 class = "number">9</h1>
</button>
<button class="button" value="+">
<h1 class = "number">+</h1>
</button>
<button class="button" value="4">
<h1 class = "number">4</h1>
</button>
<button class="button" value="5">
<h1 class = "number">5</h1>
</button>
<button class="button" value="6">
<h1 class = "number">6</h1>
</button>
<button class="button" value="-">
<h1 class = "operator">-</h1>
</button>
<button class="button" value="1">
<h1 class = "number">1</h1>
</button>
<button class="button" value="2">
<h1 class = "number">2</h1>
</button>
<button class="button" value="3">
<h1 class = "number">3</h1>
</button>
<button class="button" value="*">
<h1 class = "operator">*</h1>
</button>
<button class="button" value=".">
<h1 class = "operator">.</h1>
</button>
<button class="button" value="0">
<h1 class = "number">0</h1>
</button>
<button class="button" value="=">
<h1 class = "operator">=</h1>
</button>
<button class="button" value="/">
<h1 class = "operator">/</h1>
</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Added try catch statement.
It may not be the best solution. You should build some kind of parser, but this will also work very well.
var resultDisplayed = false;
//1++-*/4
function getButtonPress() {
var input = this.value;
if (input == "=") {
//console.log("bang");
getResult();
} else if (resultDisplayed && input < 10) {
document.getElementById("output").innerHTML = input;
resultDisplayed = false;
} else {
document.getElementById("output").innerHTML += input;
//console.log(input);
resultDisplayed = false;
}
}
window.onload = function() {
[].slice.call(document.getElementsByClassName("button")).forEach(function(e) {
e.addEventListener('click', getButtonPress);
});
};
function getResult() {
try{
var result = document.getElementById("output").innerHTML;
var resultCalculated = eval(result);
console.log(resultCalculated);
document.getElementById("output").innerHTML = resultCalculated;
resultDisplayed = true;
}catch(e){
console.log("Invalid expression");
document.getElementById("output").innerHTML = 0;
}
}
/* Fonts from Google Fonts - more at https://fonts.google.com */
#import url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');
#import url('https://fonts.googleapis.com/css?family=Merriweather:400,700');
body {
background-color: white;
font-family: "Open Sans", sans-serif;
font-size: 18px;
color: #444;
text-align: center;
}
h1 {
font-family: "Merriweather", serif;
font-size: 32px;
}
#calculator {
width: 250px;
height: 400px;
position: absolute;
background-color: grey;
padding: 15px;
box-shadow: 5px 5px 5px 5px;
margin: auto;
}
.button {
width: 19%;
height: 70px;
box-shadow: 1px 1px 1px 1px;
border: 1px solid black;
display: inline-block;
margin: 5px;
}
.buttonContainer {
width: 95%;
margin: auto;
margin-top: 10px;
}
#screen {
width: 90%;
height: 15%;
background-color: green;
margin: auto;
color: white;
text-align: right;
overflow: hidden;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Calculator</h1>
<div id="calculator">
<div id="screen">
<h1 id="output">0</h1>
</div>
<div class="buttonContainer">
<button class="button" value="7">
<h1 class = "number">7</h1>
</button>
<button class="button" value="8">
<h1 class = "number">8</h1>
</button>
<button class="button" value="9">
<h1 class = "number">9</h1>
</button>
<button class="button" value="+">
<h1 class = "number">+</h1>
</button>
<button class="button" value="4">
<h1 class = "number">4</h1>
</button>
<button class="button" value="5">
<h1 class = "number">5</h1>
</button>
<button class="button" value="6">
<h1 class = "number">6</h1>
</button>
<button class="button" value="-">
<h1 class = "operator">-</h1>
</button>
<button class="button" value="1">
<h1 class = "number">1</h1>
</button>
<button class="button" value="2">
<h1 class = "number">2</h1>
</button>
<button class="button" value="3">
<h1 class = "number">3</h1>
</button>
<button class="button" value="*">
<h1 class = "operator">*</h1>
</button>
<button class="button" value=".">
<h1 class = "operator">.</h1>
</button>
<button class="button" value="0">
<h1 class = "number">0</h1>
</button>
<button class="button" value="=">
<h1 class = "operator">=</h1>
</button>
<button class="button" value="/">
<h1 class = "operator">/</h1>
</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
The final else in getButtonPress has to look like this:
else {
var operators = ["+", "-", "*", "/", "."],
lastCharacter = document.getElementById("output").innerHTML[document.getElementById("output").innerHTML.length - 1];
if(!operators.includes(lastCharacter) || !operators.includes(input)){
document.getElementById("output").innerHTML += input;
console.log(input);
resultDisplayed = false;
}
}
Intuitively,
!operators.includes(lastCharacter) || !operators.includes(input)
can be thought of as the logical expression
operators.includes(lastCharacter) → ¬operators.includes(input)
which means “if the last character is an operator, the next input isn’t an operator”. if this is the case, the symbol is added to the output screen, otherwise it isn’t.
This still won’t prevent you from entering numbers like 2.5.6 or ending the expression with an operator, but this solves the described problem.
another option, delete 0 in start and delete operands in last character when getResult() called
var resultDisplayed = false;
function getButtonPress() {
var input = this.value,
output = document.getElementById("output");
if(input == "=") {
//console.log("bang");
getResult();
}
else if(resultDisplayed && input < 10) {
output.innerHTML = input;
resultDisplayed = false;
}
else {
//console.log(input);
var currentValue = output.innerHTML;
// start with 0 + digit, delete it
if((currentValue+input).match(/^0\d/)){
input = input;
}
// end with +-*/ delete it
else if(currentValue.match(/[-\+\*\/]$/) && input.match(/[-\+\*\/]/)) {
input = currentValue.slice(0, -1) +''+ input;
}
else{
input = currentValue + input
}
output.innerHTML = input;
resultDisplayed = false;
}
}
[].slice.call(document.getElementsByClassName("button")).forEach(function(e) {
e.addEventListener('click', getButtonPress);
});
function getResult() {
var result = document.getElementById("output").innerHTML;
if(result.match(/[-\+\*\/]$/))
result = result.slice(0, -1);
var resultCalculated = eval(result);
console.log(resultCalculated);
document.getElementById("output").innerHTML = resultCalculated;
resultDisplayed = true;
}
#import url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');
#import url('https://fonts.googleapis.com/css?family=Merriweather:400,700');
body {
background-color: white;
font-family: "Open Sans", sans-serif;
font-size: 18px;
color: #444;
text-align: center;
}
h1 {
font-family: "Merriweather", serif;
font-size: 32px;
}
#calculator {
width: 250px;
height: 400px;
position: absolute;
background-color: grey;
padding: 15px;
box-shadow: 5px 5px 5px 5px;
margin: auto;
}
.button {
width: 19%;
height: 70px;
box-shadow: 1px 1px 1px 1px;
border: 1px solid black;
display: inline-block;
margin: 5px;
}
.buttonContainer {
width: 95%;
margin: auto;
margin-top: 10px;
}
#screen {
width: 90%;
height: 15%;
background-color: green;
margin: auto;
color: white;
text-align: right;
overflow: hidden;
}
<h1>Calculator</h1>
<div id="calculator">
<div id="screen">
<h1 id="output">0</h1>
</div>
<div class="buttonContainer">
<button class="button" value="7">
<h1 class="number">7</h1>
</button>
<button class="button" value="8">
<h1 class="number">8</h1>
</button>
<button class="button" value="9">
<h1 class="number">9</h1>
</button>
<button class="button" value="+">
<h1 class="number">+</h1>
</button>
<button class="button" value="4">
<h1 class="number">4</h1>
</button>
<button class="button" value="5">
<h1 class="number">5</h1>
</button>
<button class="button" value="6">
<h1 class="number">6</h1>
</button>
<button class="button" value="-">
<h1 class="operator">-</h1>
</button>
<button class="button" value="1">
<h1 class="number">1</h1>
</button>
<button class="button" value="2">
<h1 class="number">2</h1>
</button>
<button class="button" value="3">
<h1 class="number">3</h1>
</button>
<button class="button" value="*">
<h1 class="operator">*</h1>
</button>
<button class="button" value=".">
<h1 class="operator">.</h1>
</button>
<button class="button" value="0">
<h1 class="number">0</h1>
</button>
<button class="button" value="=">
<h1 class="operator">=</h1>
</button>
<button class="button" value="/">
<h1 class="operator">/</h1>
</button>
</div>
</div>
Here is the Code that will not accept multiple operands
function calc(opr)
{
var a2=0;
var a1 = cal.display.value;
a2 = a1.charAt(a1.length-1);
if(a2 == '/' || a2 == '+' || a2 == '-' || a2 == '*')
{
cal.display.value = a1.substring(0,a1.length-1);
cal.display.value += opr;
}
else
{
cal.display.value+= opr;
}
}
Whenever you click any operand button you need to take the last val from the input and see if its one of the operands, if it is skip like below.
$('#button-plus').click(function() {
var lastChar = $('#disp').val().slice(-1);
var firstChar = $('#disp').val().slice(0);
if (lastChar == '*' || lastChar == '-' || lastChar == '+' || lastChar == '/' || lastChar == '.' || lastChar == '(' || lastChar == '%'){
// DO NOTHING
}
else if (firstChar == '0'){
// DO NOTHING
}
else {
addChar(this.form.display, '+');
}
$('#disp').removeClass("result");
dotCount = 0;
});

Repeat words inside a loop

I am new to programming using JavaScript. How do I repeat a string value retrieved from an <input type="text"> element value, repeat the string by the number retrieved from a sibling <input> element, then set the .innerHTML of a <div> element to the resulting repeated string using JavaScript? I have tried the below approach, which did not return expected result. What am I doing wrong at my current attempt? Is there a simpler way to achieve the expected result?
function repeatWord(str, num) {
num = Number(num);
var result = '';
while (true) {
if (num & 1) { // (1)
result += str;
}
num >>>= 1; // (2)
if (num <= 0) break;
str += str;
}
return result;
}
</script>
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: #D3D3D3;
font-family: arial;
text-align: right;
color: #008B8B;
}
#contentwrap {
border: 8px #800000 solid;
padding: 20px;
width: 600px;
border-radius: 25px;
text-align: right;
background: white;
margin: 40px auto 0px auto;
}
#formwrap {
text-align: center;
margin: 0px 0px 60px 0px;
min-height: 300px;
}
#title {
font-size: 2.2em;
border-bottom: 7px #008B8B double;
padding: 10px 0px 10px 0px;
color: #008B8B;
text-align: center;
}
#formtext {
text-align: center;
margin-top: 5px;
}
.formfield {
text-align: center;
margin: 5px 20px 10px 20px;
}
#button {
border-radius: 20px;
}
#results {
font-size: 1em;
}
</style>
</head>
<body>
<div id="contentwrap">
<div id="title">Fun with Loops</div> <br />
<div id="formwrap">
<form>
<div id="formtext">Enter any word</div>
<input type="text" id="word" class="formfield" size="20" /> <br />
<div id="formtext">Enter number of times to repeat word</div>
<input type="text" id="repeatnum" class="formfield" size="20" /> <br />
<input type="button" value="Show Output" id="button" onClick="repeatWord()" />
</form>
<div id="results"></div>
</div>
</div>
</body>
</html>
<html>
<head>
<title></title>
<script type="text/javascript">
function repeatWord(str, num) {
num = Number(num);
var result = '';
while (true) {
if (num & 1) { // (1)
result += str;
}
num >>>= 1; // (2)
if (num <= 0) break;
str += str;
}
return result;
}
</script>
<style type="text/css">
body {
background-color: #D3D3D3;
font-family: arial;
text-align: right;
color: #008B8B;
}
#contentwrap {
border: 8px #800000 solid;
padding: 20px;
width: 600px;
border-radius: 25px;
text-align: right;
background: white;
margin: 40px auto 0px auto;
}
#formwrap {
text-align: center;
margin: 0px 0px 60px 0px;
min-height: 300px;
}
#title {
font-size: 2.2em;
border-bottom: 7px #008B8B double;
padding: 10px 0px 10px 0px;
color: #008B8B;
text-align: center;
}
#formtext {
text-align: center;
margin-top: 5px;
}
.formfield {
text-align: center;
margin: 5px 20px 10px 20px;
}
#button {
border-radius: 20px;
}
#results {
font-size: 1em;
}
</style>
</head>
<body>
<div id="contentwrap">
<div id="title">Fun with Loops</div> <br />
<div id="formwrap">
<form>
<div id="formtext">Enter any word</div>
<input type="text" id="word" class="formfield" size="20" /> <br />
<div id="formtext">Enter number of times to repeat word</div>
<input type="text" id="repeatnum" class="formfield" size="20" /> <br />
<input type="button" value="Show Output" id="button" onClick="repeatWord()" />
</form>
<div id="results"></div>
</div>
</div>
</body>
</html>
The function repeatWord returns expected result.
The issue is that you do not pass any parameters to the function, the return value from the function is not further processed. The DOM elements are not referenced within repeatWord function call. No element has .textContent or .innerHTML set using return value of repeatWord.
Note, you can use console.log() to check a value within a function call, or the return value of a function. For example, console.log(result). See also What is the scope of variables in JavaScript?.
You can substitute input type="number" forinput type="text"as#repeatnumelement, withminattribute set to0,maxattribute set to10`, or other positive number value, as a positive number would appear to be expected value of the element.
Define variables to reference elements having ids word, repeatnum, results to reference the elements within repeatWord function call.
Get the .values from #word and #repeatnum elements; set str as #word .value, set num with #repeatnum .valueAsNumber passed to Number constructor.
At completion of while loop, set #results .textContent to result.
<div id="contentwrap">
<div id="title">Fun with Loops</div>
<br />
<div id="formwrap">
<form>
<div id="formtext">Enter any word</div>
<input type="text" id="word" class="formfield" size="20" />
<br />
<div id="formtext">Enter number of times to repeat word</div>
<input type="number" min="0" max="10" id="repeatnum" class="formfield" size="20" />
<br />
<input type="button" value="Show Output" id="button" onClick="repeatWord()" />
</form>
<br>
<div id="results"></div>
</div>
</div>
<script>
var word = document.getElementById("word");
var number = document.getElementById("repeatnum");
var results = document.getElementById("results");
function repeatWord() {
// set `num` to `number` `.valueAsNumber`
num = number.valueAsNumber;
str = word.value; // set `str` to `word` `.value`
var result = "";
while (true) {
if (num & 1) { // (1)
result += str;
}
num >>>= 1; // (2)
if (num <= 0) break;
str += str;
}
// set `results` `.textContent` to `result`
results.textContent = result;
}
</script>

Dynamically Removing Inputs / DOM Error

I've been able to make a section of a form that dynamically adds a tier of inputs on a button click. This new div is appended after the previous div and I am attempting to make a button that can also remove the tier if the user doesn't need it.
My problem is I cannot seem to remove the divs. I can add but not remove. When I look at the DOM I can see when the addDiv button is clicked, it is indeed adding the div and all the content is within the div, so it is being appended properly. But when I try to remove the newly appended div from it's parent element, I get the following error thrown:
addJob.js:18 Uncaught TypeError: Cannot read property 'parentNode' of undefinedremoveJob # addJob.js:18onclick # index.html:1
I'm unsure how to make my removeJob() function defined in a way that is just the reverse of how it was added.
CodePen: http://codepen.io/theodore_steiner/pen/WGEmGr
var i = 0;
function addJob() {
if (i <= 1) {
i++;
var div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" name="schoolBoard_' + i + '"> '+
'<input type="text" class="three-lines" name="position_' + i + '"> '+
'<input type="text" class="three-lines" name="years_' + i + '">'+
'<input type="button" value="-" onclick="removeJob()">';
document.getElementById("employmentHistory").appendChild(div);
}
}
function removeJob(div) {
document.getElementById("employmentHistory").removeChild(div.parentNode);
i--;
};
button {
height: 20px;
width: 20px;
background: none;
margin-left: 10px;
margin-top: 30px;
margin-bottom: 25px;
}
input[type="button"] {
height: 20px;
width: 20px;
background: none;
border: 1px solid #ccc;
outline: none;
margin-left: 20px;
}
input[type="button"]:focus {
outline: none;
}
input.three-lines {
margin-left: 18px;
background: none;
border: none;
border-bottom: 1px solid #b3c1cc;
width: 150px;
margin-bottom: 30px;
}
<div id="page2-content">
<div class="input-group" id="previousTeachingExperience">
<label id="teachingExpierience">Teaching Experience *</label>
<div id="employmentHistory">
<input type="text" class="three-lines" name="schoolBoard_1" placeholder="School Board" onblur="this.placeholder='Email'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="position_1" placeholder="Position" onblur="this.placeholder='Position'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="years_1" />
<input type="button" name="myButton" onclick="addJob()" value="+" />
</div>
You function is right just add the paramter "this" when you put the function in the onclick attribute, like this:
onclick="removeJob(this)"
Well, As per Below discussion passing this in the parameter is the best way to achieve this.
Below is the working code for this-
var i = 0;
var div = null;
function addJob()
{
if(i <= 1)
{
i++;
div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" name="schoolBoard_'+i+'"> <input type="text" class="three-lines" name="position_'+i+'"> <input type="text" class="three-lines" name="years_'+i+'"><input type="button" value="-" onclick="removeJob(this)">';
document.getElementById("employmentHistory").appendChild(div);
}
}
function removeJob(div)
{
document.getElementById("employmentHistory").removeChild(div.parentNode);
i--;
};
button
{
height: 20px;
width: 20px;
background: none;
margin-left: 10px;
margin-top: 30px;
margin-bottom: 25px;
}
input[type="button"]
{
height: 20px;
width: 20px;
background: none;
border: 1px solid #ccc;
outline: none;
margin-left: 20px;
}
input[type="button"]:focus
{
outline: none;
}
input.three-lines
{
margin-left: 18px;
background: none;
border: none;
border-bottom: 1px solid #b3c1cc;
width: 150px;
margin-bottom: 30px;
}
<div id="page2-content">
<div class="input-group" id="previousTeachingExperience">
<label id="teachingExpierience">Teaching Experience *</label>
<div id="employmentHistory">
<input type="text" class="three-lines" name="schoolBoard_1" placeholder="School Board" onblur="this.placeholder='Email'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="position_1" placeholder="Position" onblur="this.placeholder='Position'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="years_1" />
<input type="button" name="myButton" onclick="addJob()" value="+" />
</div>
Hoping this will help you :)

Javascript link in image

What I have are 3 images but are not online , I need to get link these three pictures to go on different pages !
each image each link
var images = [
'image/dragao1.jpg',
'image/dragao2.jpg',
'image/dragao3.jpg'
];
function slideShowForward() {
images.push(images.shift());
document.getElementById('imagesP').style.backgroundImage = 'url(' + images[0] + ')';
}
function slideShowBack() {
images.unshift(images.pop());
document.getElementById('imagesP').style.backgroundImage = 'url(' + images[0] + ')';
}
<div id="imagesP" style=" border: 1px solid black; height: 200px; width:750px;">
<div id="form">
<input type="button" value="previous" onclick="slideShowBack();" style="width: 39px; height: 34px;" />
<input type="button" value="next" onclick="slideShowForward();" style="width: 39px; height: 34px;" />
</div>
</div>
var images = [
'http://cinemacomrapadura.com.br/imagens/2014/01/20140127-como-treinar-seu-dragao1.jpg',
'http://cinemacomrapadura.com.br/imagens/2014/01/20140127-como-treinar-seu-dragao2.jpg',
'http://br.web.img2.acsta.net/c_520_690/newsv7/15/02/06/17/22/496087.jpg'
];
var hrefs=["http://www.google.com","http://www.msdn.com","http://www.yahoo.com"]
function slideShowForward() {
images.push(images.shift());
hrefs.push(hrefs.shift());
document.getElementById('imagesP').style.backgroundImage = 'url(' + images[0] + ')';
document.getElementById('imagesP').setAttribute(href,hrefs[0]);
}
function slideShowBack() {
images.unshift(images.pop());
hrefs.unshift(hrefs.pop());
document.getElementById('imagesP').style.backgroundImage = 'url(' + images[0] + ')';
document.getElementById('imagesP').setAttribute(href,hrefs[0]);
}
window.onload=function() {
document.getElementById('imagesP').onclick=function(e) {
var tgt = e.target||e.srcElement;
if (tgt.tagName.toLowerCase()=="input") e.preventDefault();
else location=this.getAttribute("href");
}
}
#imagesP { border: 1px solid black; height: 200px; width:750px; background-image: url(http://br.web.img2.acsta.net/c_520_690/newsv7/15/02/06/17/22/496087.jpg)}
<div id="imagesP" href="http://www.google.com">
<div id="form">
<input type="button" value="previous" onclick="slideShowBack();" style="width: 39px; height: 34px;" />
<input type="button" value="next" onclick="slideShowForward();" style="width: 39px; height: 34px;" />
</div>
</div>

Categories