How to stop lag when going through a for loop? - javascript

I'm generating primes, and it will lag until it's done. Is there a way where I can make it so it doesn't lag. For example, if you're generating up to 1000, I want it to just spit out the answers right away when it's done calculating the number.
HTML:
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>Prime Generator</title>
<h1>
Welcome to my online prime generator!
<h1>
<style>
.w3-gold,.w3-hover-gold:hover{color:#fff!important;background-color:#c9a000!important}
.w3-btn {
background-color: #c9a000;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 0px;
-webkit-transition-duration: 0.4s;
transition-duration: 0.4s;
cursor: pointer;
float: right;
}
}
.button1 {
background-color: black;
color: white;
}
.button1:hover {
background-color: #e7e7e7;
color: black
}
.button2 {
background-color: #c9a000;
color: white;
}
.button2:hover {
background-color: #e7e7e7;
color: black
}
</style>
</head>
<body>
<div class="w3-container">
<div class="w3-card-4">
<div class="container w3-gold">
<h2>Input Form</h2>
</div>
<form class="w3-container">
<p>
<select class="w3-select" name="option" id="option">
<option value="" disabled selected>Generate or Choose?</option>
<option value="1" >Generate</option>
<option value="2" >Choose</option>
</select>
<input class="w3-input" id="inputt" type="text">
<label class="w3-text">Type in a number<label>
</p>
<p>
<div class="w3-btn button2" id="BT2">Clear</div>
<div class="w3-btn button1" id="BT1">Proceed</div>
<div id ="done"></div>
<div id="out"></div>
<div id="gout"></div>
</form>
<script>
function prime(num) {
var stop = num % 2 == 0
var num1 = 2
var num2 = 2
while (stop == false && num2 <= Math.sqrt(num)) {
stop = num1 * num2 == num
num1++
if (num1 == num) {
num1 = 2
num2++
}
}
if (stop == true) {
return(num + " is not prime.")
} else {
return(num + " is prime")
}
}
document.getElementById("BT1").addEventListener("click", function(){
if (isNaN(document.getElementById("inputt").value) == false && document.getElementById("inputt").value != "" && document.getElementById("option").value == 1) {
document.getElementById("out").innerHTML = "<br> Generating up to " + document.getElementById("inputt").value + "!"
document.getElementById("gout").innerHTML = ""
for (num3 = 1; num3 <= parseInt(document.getElementById("inputt").value); num3++) {
document.getElementById("gout").innerHTML = document.getElementById("gout").innerHTML + "<br>" + prime(num3)
}
document.getElementById("done").innerHTML = "done!"
} else if (isNaN(document.getElementById("inputt").value) == false && document.getElementById("inputt").value != "" && document.getElementById("option").value == 2) {
document.getElementById("out").innerHTML = "Checking if " + document.getElementById("inputt").value + " is prime!"
document.getElementById("gout").innerHTML = "<br>" + prime(parseInt(document.getElementById("inputt").value))
} else if (document.getElementById("inputt").value != "") {
document.getElementById("out").innerHTML = document.getElementById("inputt").value + " is not a number!"
} else {
document.getElementById("out").innerHTML = "Thats a blank space!"
}
});
document.getElementById("BT2").addEventListener("click", function(){
document.getElementById("gout").innerHTML = ""
document.getElementById("out").innerHTML = ""
document.getElementById("done").innerHTML = ""
});
</script>
</div>
</div>
</body>
</html>

For an immediate fix, you can replace the contents of the for loop with the following:
var pr = prime(num3);
var cont = document.createTextNode(pr);
var br = document.createElement('br');
document.getElementById("gout").appendChild(br);
document.getElementById("gout").appendChild(cont);
The reason for the lag is that setting innerHTML is a very time taking operation, I guess.

Related

Changing values in column in table using buttons

i would like create a table, where one column would be variables and i want to have "+" and "-" buttons next to it. So when i click button "+" it would show number input and after submit, it would add to the value.
It works for one value, but do not get the other right, without copying whole script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table</title>
</head>
<style>
body {
background-color: lightslategray;
}
#PLA {
float: left;
width: 30%;
padding: 10px;
}
th, td {
border: 1px solid;
}
.header {
text-align: center;
font-size: 20px;
}
.celltext {
font-size: 15px;
}
.number {
text-align: center;
}
.vbutton {
background-color: gray;
border: 1px solid black;
border-radius: 6px;
color: white;
text-align: center;
text-decoration: none;
font-size: 10px;
padding: 0px;
margin-right: 4px;
width: 20px;
height: 20px;
float: right;
}
button:hover {
background-color: lightgray;
color: black;
}
.input {
padding: 0px;
width: 48px;
height: 16px;
font-size: 14px;
-webkit-appearance: none;
}
input[type = number] {
-moz-appearance: textfield;
}
input:focus {
border: 0px;
outline: 0px;
}
</style>
<body>
<table id="PLA">
<div>
PLA
<span id="test"></span>
<input type="number" class="input" id="nwpla" onchange="changewpla1()" onkeypress="return onlyNumberKey(event)">
</div>
<tr class="header">
<td>Barva</td>
<td>Výrobce</td>
<td>Hmotnost (g)</td>
<td>Cena (kg)</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla1">
<span id="wpla1"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla2">
<span id="wpla2"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
</table>
</body>
<script>
// test
test = document.getElementById("test");
// Weight of pla1
wpla1 = document.getElementById("wpla1");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla1weight = localStorage.pla1weight;
localStorage.setItem("pla1weight", pla1weight);
if (localStorage.pla1weight == "undefined" || localStorage.pla1weight == isNaN) {
localStorage.pla1weight = 0
pla1weight = 0;
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
else {
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
function changewpla1() {
x = parseInt(wpla1.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla1weight = x - y;
} else {
pla1weight = x + y;
}
wpla1.innerHTML = pla1weight;
wpla1.value = pla1weight;
localStorage.setItem("pla1weight", pla1weight);
nwpla.style.display = "none";
}
// Weight of pla2
wpla2 = document.getElementById("wpla2");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla2weight = localStorage.pla2weight;
localStorage.setItem("pla2weight", pla2weight);
if (localStorage.pla2weight == "undefined" || localStorage.pla2weight == isNaN) {
localStorage.pla2weight = 0
pla2weight = 0;
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
else {
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
function changewpla2() {
x = parseInt(wpla2.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla2weight = x - y;
} else {
pla2weight = x + y;
}
wpla2.innerHTML = pla2weight;
wpla2.value = pla2weight;
localStorage.setItem("pla2weight", pla2weight);
nwpla.style.display = "none";
}
function addpla() {
nwpla.value = 0;
p = 0;
nwpla.style.display = "";
}
function subpla() {
nwpla.value = 0
p = 1;
nwpla.style.display = "";
}
function onlyNumberKey(evt) {
var ASCIICode = (evt.which) ? evt.which : evt.keyCode
if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
return false;
return true;
}
</script>
</html>
Any idea?
I would like to have a database as last option. Every value would be saved in local storage.
Thanks.

How to add auto calculation for two inputs

I have this calculator that I'd like for the results to auto update after the the user adds input.
I've tried the .keyup thing, but I don't understand it.
I'm kinda new to javascript.
Here's my codepen for the project.
http://codepen.io/Tristangre97/pen/zNvQON?editors=0010
HTML
<div class="card">
<div class="title">Input</div>
<br>
<div id="metalSpan"><input class="whiteinput" id="numMetal" type="number">
<div class="floater">Metal Quantity</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan"><input class="whiteinput" id="numForge" type=
"number">
<div class="floater">Forge Quantity</div></div>
<br>
<input checked id="rb1" name="fuel" type="radio" value="spark"> <label for=
"rb1">Sparkpowder</label> <input id="rb2" name="fuel" type="radio" value=
"wood"> <label for="rb2">Wood</label><br>
<br>
<button class="actionButton" id="submit" type="button">Calculate</button></div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div>
<br>
<div id="result"><span id="spreadMetal"></span> metal <span class=
"plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class=
"plural"></span> forge <span id="allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br></div>
</div>
</div>
JS
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("#submit").click(function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == '') {
$("#metalAlert").html("Please enter a value");
}
else if (forges == 0 || forges == '') {
$("#metalAlert").html('');
$("#forgeAlert").html("Please enter a value");
}
else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
}
else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
}
else {
$(".plural").html("in the");
}
$("#forgeAlert").html('');
if (metals % 2 == 0) {}
else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(((spread / 2) * 20) / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
}
else {
$("#allSpark").html(String(''));
}
$("#timeSpark").html(String((isWood) ? (sparks / 2) : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html((isWood) ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
To run the function whenever something is inputted in the field, try the
$("input").on('input', function() { .. });
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("input").on('input', function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == "") {
$("#metalAlert").html("Please enter a value");
} else if (forges == 0 || forges == "") {
$("#metalAlert").html("");
$("#forgeAlert").html("Please enter a value");
} else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
} else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
} else {
$(".plural").html("in the");
}
$("#forgeAlert").html("");
if (metals % 2 == 0) {
} else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(spread / 2 * 20 / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
} else {
$("#allSpark").html(String(""));
}
$("#timeSpark").html(String(isWood ? sparks / 2 : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html(isWood ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
body {
background-color:#316b6f;
font-family:Helvetica,sans-serif;
font-size:16px;
}
.whiteinput {
outline: none;
border-width: 0px;
margin: 0;
padding: .5em .6em;
border-radius: 2px;
font-size: 1em;
color: #316b6f;
}
.actionButton {
background-color: #316B6F;
color: #fff;
padding: .5em .6em;
border-radius: 3px;
border-width: 0px;
font-size: 1em;
cursor: pointer;
text-decoration: none;
-webkit-transition: all 250ms;
transition: all 250ms;
}
.actionButton:hover {
color: #fff;
}
.actionButton:active {
background: #BBFF77;
color: #316B6F;
-webkit-transition: all 550ms;
transition: all 550ms;
}
.card {
position: relative;
background: #4E8083;
color:#FFFFFF;
border-radius:3px;
padding:1.5em;
margin-bottom: 3px;
}
.title {
background: #76B167;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.title2 {
background: #2F3A54;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.floater {
padding: 3px;
}
.radiobtn {
background: red;
border-radius: 2px;
}
input[type=radio] + label:before {
content: "";
display: inline-block;
width: 20px;
height: 20px;
vertical-align:middle;
margin-right: 8px;
background-color: #aaa;
margin-bottom: 6px;
border-radius: 2px;
-webkit-transition: all 450ms;
transition: all 450ms;
}
input[type=radio], input[type=checkbox] {
display:none;
}
input[type=radio]:checked + label:before {
content: "\2022"; /* Bullet */
color:white;
background-color: #fff;
font-size:1.8em;
text-align:center;
line-height:14px;
margin-right: 8px;
}
input[type=checkbox]:checked + label:before {
content:"\2714";
color:white;
background-color: #fff;
text-align:center;
line-height:15px;
}
*:focus {
outline: none;
}
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="card">
<div class="title">Input</div><br>
<div id="metalSpan">
<input class="whiteinput" id="numMetal" type="number">
<div class="floater">
Metal Quantity
</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan">
<input class="whiteinput" id="numForge" type="number">
<div class="floater">
Forge Quantity
</div>
</div>
<br>
<input type="radio" id="rb1" name="fuel" value="spark" checked>
<label for="rb1">Sparkpowder</label>
<input type="radio" id="rb2" name="fuel" value="wood">
<label for="rb2">Wood</label><br><br>
<button class="actionButton" id="submit"
type="button">Calculate</button>
</div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div><br>
<div id="result">
<span id="spreadMetal"></span> metal <span class="plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class="plural"></span> forge <span id=
"allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br>
</div>
</div>
</div>
Codepen
It is triggering your errors because that is part of your function.
More info regarding the input method.
Look, you have two options:
Put all your algorithm of submit click into a function and call him into two binds: the submit click and input change (on('change')) or just remove your calculate button and rely the calculation into onchange of the inputs: each change of checks or inputs will trigger the calculation of metals. The second approach it's more interesting for me and removes the necessity to the user clicks to calculate (he already clicked into inputs and checks). Obviously you can add a filter to only allow to calculation function run after a certain minimum number of data filled, it's a good idea to avoid poor results resulted by lack of data.
In order to auto update calculation, we have to listen to users input on input elements. The easiest approach with minimum changes to existing code is to add input events and emit click on the button:
$("#numMetal, #numForge").on('input', function(){
$("#submit").click()
})
Better approach is to move calculation logic to separate function and call it on desirable events:
$("#numMetal, #numForge").on('input', function(){
calculate()
})
$("#submit").click(function(){
calculate()
})
This will keep the code structured and easier to follow.
Try this:
$( "#numMetal, #numForge" ).keyup(function(event) {
console.log('a key has been pressed');
// add code to handle inputs here
});
What happens here is that an event listener - the key up event - is bound to the two inputs you have on your page. When that happens the code inside will be run.
As suggested in other comments it would be a good idea to call a separate method with all the input processing code you have in the submit call, this way you will avoid code duplication.
You will also want to bind events to the checkboxs. This can be achieved with this:
$( "input[name=fuel]" ).on('change',function() {
console.log('checkbox change');
// call processing method here
});

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>

Missing word game (gap filler)

i am making a little word game where theres a missing word and if you fill in the input field with the correct answer it turns green
I would like to add a functionality to this code but I am not sure how
I want to edit it so if you put a wrong answer in it turns red
at the minute it just adds up your score and turns green if you put in the right answer
i know the answer is to do with the end of the js file where it turns it green if correct
this is the html
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'> </script>
<script type="text/javascript">
$(document).ready(function(){
$("input").not( $(":button") ).keypress(function (evt) {
if (evt.keyCode == 13) {
iname = $(this).val();
if (iname !== 'Submit'){
var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select');
var index = fields.index( this );
if ( index > -1 && ( index + 1 ) < fields.length ) {
fields.eq( index + 1 ).focus();
}
return false
}
}
});
});</script>
<script type="text/javascript" src="prolinguis-gap-filler.js"></script>
<div style="font-family:Helvetica; font-size: 18px; vertical-align:bottom; color:#3e2e41; margin:16px 0;"> Score: <label id="label_score">0%</label></div>
<form class="game-form" style="padding: 0px; width: 100%; margin: 10px auto;" >
<!-- //////////////////////////////////////////////////////////////////////////////////////// -->
<div class="game-hold" style=" width: 100%; text-align: left; display: inline-block;">
<p style="font-size: 14px; font-weight: bold; margin: 5px 0; color: #333333;">Question 1</p>
<p>Where is Stephen from? <input TYPE="text" id="ctr1" onBlur="validate(this.value, this.id)" style="text-transform: uppercase; font-family:Helvetica; font-size: 10px; width:150px; height:18px; text-align: left; color:#000000;"></input></p>
</div>
<!-- //////////////////////////////////////////////////////////////////////////////////////// -->
<div class="game-hold" style=" width: 100%; text-align: left; display: inline-block;">
<p style="font-size: 14px; font-weight: bold; margin: 5px 0; color: #333333;">Question 2</p>
<p>If someone asks you, what’s cooking? You shouldn’t answer with: <input TYPE="text" id="ctr2" onBlur="validate(this.value, this.id)" style="text-transform: uppercase; font-family:Helvetica; font-size: 10px; width:150px; height:18px; text-align: left; color:#000000;"></input></p>
</div>
<!-- //////////////////////////////////////////////////////////////////////////////////////// -->
<div class="game-hold" style=" width: 100%; text-align: left; display: inline-block;">
<p style="font-size: 14px; font-weight: bold; margin: 5px 0; color: #333333;">Question 3</p>
<p>Instead, just say <input TYPE="text" id="ctr3" onBlur="validate(this.value, this.id)" style="text-transform: uppercase; font-family:Helvetica; font-size: 10px; width:150px; height:18px; text-align: left; color:#000000;"></input></p>
</div>
</form>
and in a js file i have this
<script>
var ctr = 0
var score_ctr = 0
function validate(value, id) {
if (id =='ctr1' && (value.toUpperCase()=="UNITED STATES" || value.toUpperCase()=="USA" || value.toUpperCase()=="AMERICA")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value="UNITED STATES";
}
if (id =='ctr2' && (value.toUpperCase()=="GOOD")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value="GOOD";
}
if (id =='ctr3' && (value.toUpperCase()=="NOTHING MUCH" || value.toUpperCase()=="NOT MUCH")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value="NOTHING MUCH";
}
}
function correct_answer (id) {
score_ctr = (ctr * 100) / 3
document.getElementById('label_score').innerHTML = score_ctr.toFixed(0) + '%'
document.getElementById(id).disabled=true;
document.getElementById(id).style.backgroundColor = '#c1d82f'
document.getElementById(id).style.cursor="default"
}
</script>
Change validate(value, id) to the following:
function validate(value, id) {
if (id == 'ctr1' && (value.toUpperCase() == "UNITED STATES" || value.toUpperCase() == "USA" || value.toUpperCase() == "AMERICA")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value = "UNITED STATES";
}
else if (id == 'ctr2' && (value.toUpperCase() == "GOOD")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value = "GOOD";
}
else if (id == 'ctr3' && (value.toUpperCase() == "NOTHING MUCH" || value.toUpperCase() == "NOT MUCH")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value = "NOTHING MUCH";
}
else
{
document.getElementById(id).style.backgroundColor = '#ff0000';
document.getElementById(id).style.cursor = "default";
}
This will go through and check all the different input fields, and if no correct answer is found, will set the background of the last blurred field to red.
Just a hint, if you want to clean up your code a bit, consider using a switch statement to determine which id you're checking.

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>

Categories

Resources