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>
Related
So I taught myself coding a few years ago, and got it just enough to put together a few tools for work. I recently had to migrate my site out of CodePen and onto an actual web server. Now I'm having an issue where part of my javascript is executing properly (a portion that empties all other input fields when a user enters an input field using JQuery), but the button that calculates an answer will not work. I believe the .click is not picking it up. Either way I'm not getting error messages, the button just does nothing when I press it.
When I put the code in a snippet to share with you guys, it works (just like it did in CodePen), but the exact same code on my web host does not work. I'm really at a loss here and any help would be greatly appreciated. I feel like I'm missing some small line of code that's supposed to be included in all web files.
$(document).ready(function() {
//Clear out input fields when not selected
$("#sg").focusin(function() {
$("#density").val("");
});
$("#density").focusin(function() {
$("#sg").val("");
});
$("#pounds").focusin(function() {
$("#grams").val("");
$("#percentage").val("");
});
$("#grams").focusin(function() {
$("#percentage").val("");
$("#pounds").val("");
});
$("#percentage").focusin(function() {
$("#pounds").val("");
$("#grams").val("");
});
$(".input_field").focusin(function() {
$("#density").removeClass('highlight');
$("#sg").removeClass('highlight');
$("#pounds").removeClass('highlight');
$("#grams").removeClass('highlight');
$("#percentage").removeClass('highlight');
});
//Calculate on press of enter
$("#button").keypress(function(e) {
if (e.which == 13) {
alert("this is working");
}
});
$("#button").click(function() {
calculateButton();
});
//Calculate values on button hit
function calculateButton() {
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
function removeCommas(x) {
x = x.replace(",", "");
return x;
}
var results = 0;
//Pulling information from input cells
var densityStr = document.getElementById("density").value;
var sgStr = document.getElementById("sg").value;
var poundsStr = document.getElementById("pounds").value;
var gramsStr = document.getElementById("grams").value;
var percentageStr = document.getElementById("percentage").value;
//remove commas from string and then convert string to number
var densityNum = Number(removeCommas(densityStr));
var sgNum = Number(removeCommas(sgStr));
var poundsNum = Number(removeCommas(poundsStr));
var gramsNum = Number(removeCommas(gramsStr));
var percentageNum = Number(removeCommas(percentageStr));
if (densityStr.length !== 0) {
var sgConversion = densityNum / 8.3454;
$("#sg").val(sgConversion.toFixed(3));
$("#density").addClass('highlight');
} else if (sgStr.length !== 0) {
var densityConversion = sgNum * 8.3454;
$("#density").val(densityConversion.toFixed(3));
$("#sg").addClass('highlight');
}
if (poundsStr.length !== 0) {
$("#pounds").addClass("highlight");
densityNum = document.getElementById("density").value;
var gramsConversion = poundsNum * 119.83;
var percentageConversion = poundsNum / densityNum * 100;
$("#grams").val(gramsConversion.toFixed(0));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (gramsStr.length !== 0) {
$("#grams").addClass("highlight");
densityNum = document.getElementById("density").value;
var poundsConversion = gramsNum / 119.83;
var percentageConversion = poundsConversion / densityNum * 100;
$("#pounds").val(poundsConversion.toFixed(2));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (percentageStr.length !== 0) {
$("#percentage").addClass("highlight");
densityNum = document.getElementById("density").value;
var percentageDec = percentageNum / 100;
var poundsConversion = densityNum * percentageDec;
var gramsConversion = poundsConversion * 119.83;
$("#pounds").val(poundsConversion.toFixed(2));
$("#grams").val(gramsConversion.toFixed(2));
}
}
});
body {
margin: 0;
font-family: 'Lato', sans-serif;
background: #d2d2d2;
}
p {
text-align: center;
}
conatiner {
max-width: 1024px;
margin: 0 auto;
}
#navbarContainer {
background: #F44336;
overflow: hidden;
width: 100%;
margin: 0;
}
.navbar {
float: left;
display: block;
font-family: 'Lato', sans-serif;
height: 40px;
width: 200px;
line-height: 40px;
text-align: center;
background: #F44336;
text-decoration: none;
color: #212121;
}
.navbar:hover {
background: #E57373;
color: white;
}
.active {
background: #C62828;
color: white;
}
#formContainer {
width: 450px;
background: #FDFFFC;
margin: 50px auto;
padding: 0px;
border-radius: 8px;
overflow: hidden;
}
#formContainer header {
width: 100%;
height: 130px;
background-color: #3cba54;
overflow: auto;
color: white;
}
header h1 {
margin: 35px 0 0 0;
text-align: center;
line-height: 30px;
}
header h3 {
line-height: 40px;
text-align: center;
margin: 0;
}
#heading {
background-color: #3cba54;
height: 40px;
color: white;
margin-bottom: 25px;
margin-left: -30px;
}
#heading h3 {
line-height: 40px;
}
form {
padding: 20px 0 0 20px;
text-align: center;
}
label {
display: inline-block;
width: 220px;
text-align: right;
}
#myForm .input_field {
margin-left: 20px;
margin-bottom: 10px;
font-size: 20px;
padding-left: 10px;
width: 125px;
height: 35px;
font-size: 17px;
border-radius: 3px;
background-color: #E0E0E0;
border: none;
}
#button {
display: block;
border-radius: 6px;
width: 200px;
height: 50px;
padding: 8px 15px 8px 15px;
margin: 0 auto;
margin-bottom: 50px;
font-size: 16px;
box-shadow: 0 6px #540000;
background-color: #FF3636;
border: none;
outline: none;
}
#button:active {
background-color: #B81B1B;
box-shadow: 0 1px #27496d;
transform: translateY(5px);
}
.highlight {
background: #FFEB3B !important;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
</body>
</html>
Sometimes putting script tags before the elements on the page can cause issues. You can try to put the scripts at the bottom of the body like this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
I have a simple "dice" roller, where the user can choose how many sides and how many dice based on input.
My issue is that if the user selects a large number of dice, it will force the page to scroll left in order to view the other dice.
I have tried to keep these dice within a div , even trying word-wrap: break-word; within the css, but this stacks the dice on top of eachother.
heres my code.
$(document).ready(function() {
$('#autoLoadR').click(function() {
$('#buttnLodr').html("");
if ($('#sideNum').val() < 100) {
if ($('#diceNum').val() < 20) {
for (i = 0; i < $('#diceNum').val(); i++) {
let index = i + 1;
let roll = index;
sidesAmount = $('#sideNum').val();
roll = Math.floor(Math.random() * sidesAmount) + 1;
$('#buttnLodr').append("<span id='diceBox'>" + roll + "</span>")
}
} else {
alert("Please enter a number for less than 20 for number of dice")
}
} else {
alert("Please enter a number less than 100 for number of sides")
}
});
});
body {
background: #add8e6;
margin-left: 2%;
margin-top: 2%;
width: 500px;
}
#spaceR {
color: lightblue;
}
.rollMeNow {
display: block;
color: #fff;
cursor: pointer;
border: 1px solid #d7d7d7;
font-size: 72px;
height: 156px;
line-height: 156px;
width: 256px;
background: #df1f3b;
border-radius: 4px;
text-align: center;
}
#optionDice {
border: solid;
width: 100%;
}
#diceBox {
border: solid;
padding: 7px 14px;
box-shadow: 10px 5px;
margin: 2%;
}
#rollTable {
width: 100%;
background: #fff;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://aaronlilly.github.io/CDN/css/bootstrap.min.css">
<div id="optionDice">
<h1>Number of Dice :
<span id='spaceR'> :</span>
<input type="text" id="diceNum" placeholder="Dice" size="5" style="margin-top: 10px;padding-bottom: 5px;padding-top: 4px;">
</h1>
<h1>Number of Sides :
<input type="text" id="sideNum" placeholder="Sides" size="5" style="margin-top: 10px;padding-bottom: 5px;padding-top: 4px;">
</h1>
</div>
<br><br>
<div class="rollMeNow" caption="Populate" id="autoLoadR">Roll</div>
<br>
<h1>
<div id='rollTable'>
<br>
<div class="container">
<div class="row">
<!-- <div class="col-sm"> -->
<div id='buttnLodr'> </div>
</div>
</div>
</div>
</div>
</h1>
#diceBox {
// ...
display: inline-block;
}
Also, some other suggestions:
you have some implicitly declared variables (i in your for loop and sidesAmount in that loop)
use const instead of let whenever you are not re-asigning a variable
why looping from 0, then add 1 and then store it to another variable. And then you overwrite that variable with Math.floor
try to avoid selecting DOM elements (event if its only single) by IDs. Always use class.
I have a design problem in the script that gives me the values of the right column (ignoring the values on the left), and the result of the sume I can not see in the green box when I click on "View Result"
// Old script
/*window.sumInputs = function() {
var inputs = document.getElementsByTagName('input'),
result = document.getElementById('total'),
sumar = 0;
for(var i=0; i<inputs.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sumar += parseInt(ip.value) || 0;
}
}
result.value = sumar;
}*/
// ========================
// New script
$(document).ready(function() {
var valores = $('#derecha').children();
var suma = 0;
$.each(valores, function() {
valor = $(this).val() || 0;
suma += parseInt(valor);
});
//console.log(suma);
valores = document.getElementById('total');
});
body p {
margin: 0 20px
}
/*#izquierda {display:none}*/
#izquierda,
#derecha {
display: inline-block;
vertical-align: top;
width: 140px;
margin: 20px 20px 20px 20px;
padding: 10px;
border: 1px solid #000
}
#izquierda span,
#derecha span,
body span {
font-weight: bold
}
#izquierda p,
#derecha p {
margin: 5px auto 15px;
text-align: center
}
input {
width: 80px;
display: block;
margin: 5px auto;
padding: 2px 0;
background: #f2f2f2;
border: none;
border: 1px solid #000;
text-align: center
}
#cont-resultado {
text-align: center;
width: 120px;
padding-left: 40px
}
#cont-resultado input {
display: inline-block;
margin: 0 auto 10px;
background: red;
color: #fff;
border: none;
padding: 10px 0
}
#cont-resultado a {
display: inline-block;
text-decoration: none;
color: #fff;
background: green;
padding: 10px 12px
}
#total {
display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="izquierda">
<p><span>DIV LEFT</span><br>display="none"</p>
<input name="qty1" value="240">
<input name="qty2" value="862">
<input name="qty3" value="911">
<input name="qty4" value="">
<input name="qty5" value="">
<input name="qty6" value="">
<input name="qty7" value="">
<input name="qty8" value="">
</div>
<!-- ================ -->
<div id="derecha">
<p><span>DIV RIGHT</span><br>display="block"</p>
<input name="qty1" value="2">
<input name="qty2" value="2">
<input name="qty3" value="2">
<input name="qty4" value="">
<input name="qty5" value="">
<input name="qty6" value="">
<input name="qty7" value="">
<input name="qty8" value="">
</div>
<!-- ================ -->
<div id="cont-resultado">
<input name="total" id="total">
See total
</div>
<br>
<p>What I am looking for is that only the RIGHT column is sumed, ignoring the values in the left column. <br><br><span>The result of example (6) must be seen in the red box...</span></p>
What am I doing wrong...?
Thanks in advance!
$(document).ready(function(){
var valores = $('#derecha').children();
var suma = 0;
$.each(valores,function(){
valor = $(this).val() || 0;
suma += parseInt( valor );
});
//console.log(suma);
valores = document.getElementById('total');
});
You're not doing anything with suma, further, use a selector for the children .children('input').
$(document).ready(function() {
function sumInputs(e) {
e.preventDefault();
var valores = $('#derecha').children('input');
var suma = 0;
$.each(valores, function() {
valor = $(this).val();
suma += Number(valor);
});
valores = document.getElementById('total');
$(valores).val(suma);
}
$('#sumup').on('click', sumInputs);
});
body p { margin: 0 20px}/*#izquierda {display:none}*/#izquierda,#derecha { display: inline-block; vertical-align: top; width: 140px; margin: 20px 20px 20px 20px; padding: 10px; border: 1px solid #000}#izquierda span,#derecha span,body span { font-weight: bold}#izquierda p,#derecha p { margin: 5px auto 15px; text-align: center}input { width: 80px; display: block; margin: 5px auto; padding: 2px 0; background: #f2f2f2; border: none; border: 1px solid #000; text-align: center}#cont-resultado { text-align: center; width: 120px; padding-left: 40px}#cont-resultado input { display: inline-block; margin: 0 auto 10px; background: red; color: #fff; border: none; padding: 10px 0}#cont-resultado a { display: inline-block; text-decoration: none; color: #fff; background: green; padding: 10px 12px}#total { display: block}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="izquierda"> <p><span>DIV LEFT</span><br>display="none"</p> <input name="qty1" value="240"> <input name="qty2" value="862"> <input name="qty3" value="911"> <input name="qty4" value=""> <input name="qty5" value=""> <input name="qty6" value=""> <input name="qty7" value=""> <input name="qty8" value=""></div><!-- ================ --><div id="derecha"> <p><span>DIV RIGHT</span><br>display="block"</p> <input name="qty1" value="2"> <input name="qty2" value="2"> <input name="qty3" value="2"> <input name="qty4" value=""> <input name="qty5" value=""> <input name="qty6" value=""> <input name="qty7" value=""> <input name="qty8" value=""></div><!-- ================ --><div id="cont-resultado"> <input name="total" id="total"> <a id='sumup' href="#">See total</a></div><br><p>What I am looking for is that only the RIGHT column is sumed, ignoring the values in the left column. <br><br><span>The result of example (6) must be seen in the red box...</span></p>
You need to set the value of valores (the new one) to suma:
valores.val(suma);
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.
So I am trying to get the user to input two numbers, then click a button to run a JS function and display the result on the page. However, when I run the code, it spits back
NaN
How do I solve this problem? Is there a way I can get the tip to display on the web page?
My HTML:
<!DOCTYPE html>
<html>
<head>
<title> Tip Calculator by Jonah </title>
<div id = "links">
<script src = "functions.js"></script>
<link type = "text/css" rel = stylesheet href = "design.css">
<link href="https://fonts.googleapis.com/css?family=Bitter" rel="stylesheet">
</div>
</head>
<body>
<div id = "cool_main">
<h1 id = "title"> Tip Calculator </h1>
<h2 id = "developer"> Developed by Jonah Johnson </h2>
</div>
<p id = "main_para"><b> Enter the meal cost then a tax percentage,and hit OK!</b></p>
<form id = "meal_cost">
Meal Total Here :<br>
<input type="text" id = "meal__cost" name="mealcost" /><br>
</form>
<form id = "tax_percent">
Tax Here (in percent) :<br>
<input type ="text" id = "tax_per" name="taxpercent" ><br>
</form>
<h4 id = "per"> % </h4>
<button id = "getTip" onclick = "addTogether()"> OK </button>
</body>
</html>
My JS:
var taxValue = document.getElementById("tax_per").value;
var meal__Cost = document.getElementById("meal__cost").value;
function addTogether() {
document.write(taxValue * meal__cost);
}
My CSS:
div {
position: relative;
left: -490px;
}
#title {
font-family: "Bitter", sans-serif;
border: 0px solid black;
width: 225px;
padding: 10px 24px;
background-color: #dbdbcb;
border-radius: 4px;
box-shadow: 10px 10px 5px #888888;
position: relative;
left: 531px;
font-size: 40px;
text-align: center;
}
#developer {
font-family: "Bitter", sans-serif;
border: 0px solid black;
width: 300px;
padding : 5px 10px;
text-align: center;
background-color: #dbdbcb;
border-radius: 10px 10px;
box-shadow: 10px 10px 5px #888888;
position: relative;
left: 510px;
}
#main_para {
border: 1px solid black;
width: 415px;
position: relative;
left: 0px;
font-family: "Bitter", sans-serif;
padding: 4px 10px;
background-color: #dbdbcb;
border-radius: 10px 10px;
}
#meal_cost {
border: 0px solid black;
width: 400px;
height: 100px;
padding: 10px 10px;
text-align: center;
font-family: "Bitter", sans-serif;
background-color: #dbdbcb;
box-shadow: 10px 10px 5px #888888;
position: relative;
left: 550px;
bottom: 200px;
font-size: 40px;
}
#tax_percent {
border: 0px solid black;
width: 400px;
padding: 10px 10px;
text-align: center;
font-family: "Bitter", sans-serif;
font-size: 40px;
background-color: #dbdbcb;
position: relative;
box-shadow: 10px 10px 5px #888888;
left: 550px;
bottom: 170px;
}
#per {
position: relative;
left: 856px;
bottom: 226px;
width: 10px;
font-family: "Bitter", sans-serif;
}
Any help would be appreciated. It would also be good if the displayed value was customizable in css.
function addTogether() {
var taxValue = parseInt(document.getElementById("tax_per").value);
var meal__Cost = parseInt(document.getElementById("meal__cost").value);
document.write(taxValue * meal__Cost);
}
<div id = "cool_main">
<h1 id = "title"> Tip Calculator </h1>
<h2 id = "developer"> Developed by Jonah Johnson </h2>
</div>
<p id = "main_para"><b> Enter the meal cost then a tax percentage,and hit OK!</b></p>
<form id = "meal_cost">
Meal Total Here :<br>
<input type="text" id = "meal__cost" name="mealcost" /><br>
</form>
<form id = "tax_percent">
Tax Here (in percent) :<br>
<input type ="text" id = "tax_per" name="taxpercent" ><br>
</form>
<h4 id = "per"> % </h4>
<button id = "getTip" onclick = "addTogether()"> OK </button>
You need to parse it into Integer or Float, as the data you are manipulating is string
var taxValue = parseInt(document.getElementById("tax_per").value);
var meal__Cost = parseInt(document.getElementById("meal__cost").value);
You can use parseFloat as well if you reuire
You wrong with variable name case and you must retrieve the value when user clicks the button:
<!DOCTYPE html>
<html>
<head>
<title> Tip Calculator by Jonah </title>
</head>
<body>
<div id = "cool_main">
<h1 id = "title"> Tip Calculator </h1>
<h2 id = "developer"> Developed by Jonah Johnson </h2>
</div>
<p id = "main_para"><b> Enter the meal cost then a tax percentage,and hit OK!</b></p>
<form id = "meal_cost">
Meal Total Here :<br>
<input type="text" id = "meal__cost" name="mealcost" value="0" /><br>
</form>
<form id = "tax_percent">
Tax Here (in percent) :<br>
<input type ="text" id = "tax_per" name="taxpercent" value="0"><br>
</form>
<h4 id = "per"> % </h4>
<button id = "getTip" onclick = "addTogether(); return false;"> OK </button>
<div id = "links">
</div>
<script >
function addTogether() {
var taxValue = parseFloat(document.getElementById("tax_per").value);
var meal__cost = parseFloat(document.getElementById("meal__cost").value);
document.getElementById("links").innerHTML= taxValue * meal__cost;
return false;
}
</script>
</body>
</html>