Missing word game (gap filler) - javascript

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.

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.

Tic Tac Toe : simple AI

I have a project that consists in creating a tic tac toe game that contains singleplayer and multiplayer. On the multiplayer side, each player will enter his name, and the first player will choose which symbol he will play with, if he chooses x, he will start first , in the case that first player choose 0, the second player will start first. I managed to do the multiplayer part without problems, but on the singleplayer side I don't know how to implement a simple AI that picks random fields. On the singleplayer side I want to keep the same condition, if the player chooses x, he will start first, if he chooses 0, he will start second.I wonder if you can help me.
That is the multiplayer part:
//variabile globale
let x='x';
let o='0';
let player=x;
let player2=o;
let tura=x;
let currentPlayer=x;
let nume1=document.getElementById('nume1').value;
let nume2=document.getElementById('nume2').value;
function showOptions() {
if (player == o) {
document.getElementById("rx").checked = false;
document.getElementById("ro").checked = true;
}
else if (player == x) {
document.getElementById("rx").checked = true;
document.getElementById("ro").checked = false;
}
document.getElementById("optionsDlg").style.display = "block";
}
function getOptions() {
if (document.getElementById('rx').checked === true) {
player = x;
player2 = o;
tura = player;
}
else {
player = o;
player2 = x;
tura = player2;
}
document.getElementById("optionsDlg").style.display = "none";
}
function closeModal(id) {
document.getElementById(id).style.display = "none";
}
if(player==x)
{
currentPlayer==player;
}
else{
currentPlayer==player2;
}
//stores the status of the game, whether its over or still in play
let gameStatus = "Game On";
//Gets all Boxes elements
const boxes = document.getElementsByClassName("box");
//loops through all the elements
for (let i = 0; i < boxes.length; i++) {
//adds event listener to each box;
boxes[i].addEventListener("click", function() {
//checks if the box has an x or an o in it and also checks if the game is still on
if (boxes[i].innerHTML.trim() == "" && gameStatus == "Game On") {
//adds x or o for the current play in their choosen box
boxes[i].innerHTML = currentPlayer;
let nume1=document.getElementById('nume1').value;
let nume2=document.getElementById('nume2').value;
//changes player turns
currentPlayer = currentPlayer == player ? player2 : player;
//changes player's turn label on top of the game
if(currentPlayer==player){
document.getElementById(
"player"
).innerHTML = nume1.toUpperCase();}
else{
document.getElementById(
"player"
).innerHTML = nume2.toUpperCase();}
//checks 3 matching x's or o's
if (
boxes[0].innerHTML == boxes[1].innerHTML &&
boxes[1].innerHTML == boxes[2].innerHTML &&
boxes[0].innerHTML.trim() != ""
) {
showWinner(0, 1, 2);
} else if (
boxes[3].innerHTML == boxes[4].innerHTML &&
boxes[4].innerHTML == boxes[5].innerHTML &&
boxes[3].innerHTML.trim() != ""
) {
showWinner(3, 4, 5);
} else if (
boxes[6].innerHTML == boxes[7].innerHTML &&
boxes[7].innerHTML == boxes[8].innerHTML &&
boxes[6].innerHTML.trim() != ""
) {
showWinner(6, 7, 8);
} else if (
boxes[0].innerHTML == boxes[3].innerHTML &&
boxes[3].innerHTML == boxes[6].innerHTML &&
boxes[0].innerHTML.trim() != ""
) {
showWinner(0, 3, 6);
} else if (
boxes[1].innerHTML == boxes[4].innerHTML &&
boxes[4].innerHTML == boxes[7].innerHTML &&
boxes[1].innerHTML.trim() != ""
) {
showWinner(1, 4, 7);
} else if (
boxes[2].innerHTML == boxes[5].innerHTML &&
boxes[5].innerHTML == boxes[8].innerHTML &&
boxes[2].innerHTML.trim() != ""
) {
showWinner(2, 5, 8);
} else if (
boxes[0].innerHTML == boxes[4].innerHTML &&
boxes[4].innerHTML == boxes[8].innerHTML &&
boxes[0].innerHTML.trim() != ""
) {
showWinner(0, 4, 8);
} else if (
boxes[2].innerHTML == boxes[4].innerHTML &&
boxes[4].innerHTML == boxes[6].innerHTML &&
boxes[2].innerHTML.trim() != ""
) {
showWinner(2, 4, 6);
}else if(
(boxes[0].innerHTML != boxes[1].innerHTML!=boxes[2].innerHTML!=
boxes[3].innerHTML!=boxes[4].innerHTML!=boxes[5].innerHTML!=
boxes[6].innerHTML!=boxes[7].innerHTML!=boxes[8].innerHTML)
&&(boxes[0].innerHTML.trim() != "")
&&(boxes[1].innerHTML.trim() != "")
&&(boxes[2].innerHTML.trim() != "")
&&(boxes[3].innerHTML.trim() != "")
&&(boxes[4].innerHTML.trim() != "")
&&(boxes[5].innerHTML.trim() != "")
&&(boxes[6].innerHTML.trim() != "")
&&(boxes[7].innerHTML.trim() != "")
&&(boxes[8].innerHTML.trim() != "")
){
roundDraw();
}
}
});
}
function roundDraw(){
document.getElementById('message').innerHTML=`Match is a tie`;
document.getElementById("message").style.display = "block";
gameStatus="Game Over";
}
//resets the game
document.getElementById("reset").addEventListener("click", function() {
for (let i = 0; i < boxes.length; i++) {
boxes[i].innerHTML = "";
boxes[i].style.backgroundColor = "#dee9ec";
boxes[i].style.color = "black";
}
currentPlayer = "x";
document.getElementById("message").style.display = "none";
document.getElementById("player").innerHTML = "X";
gameStatus = "Game On";
});
//displays the winner
function showWinner(x, y, z) {
let nume1=document.getElementById('nume1').value;
let nume2=document.getElementById('nume2').value;
boxes[x].style.background = "#0d8b70";
boxes[x].style.color = "white";
boxes[y].style.background = "#0d8b70";
boxes[y].style.color = "white";
boxes[z].style.background = "#0d8b70";
boxes[z].style.color = "white";
if(currentPlayer==player){
document.getElementById(
"winner"
).innerHTML = nume2.toUpperCase();}
else{
document.getElementById(
"winner"
).innerHTML = nume1.toUpperCase();}
document.getElementById("message").style.display = "block";
gameStatus = "Game Over";
}
.container-out {
font-family: "Fira Sans", sans-serif;
padding: 15px 0;
}
.container-in {
width: 97%;
margin: 0 auto;
}
.table-container {
margin: 10 auto;
text-align: center;
}
.box {
min-width: 70px;
min-height: 70px;
background: #dee9ec;
text-align: center;
vertical-align: center;
font-size: 50px;
font-weight: 900;
cursor: pointer;
}
.box:hover {
opacity: 0.7;
}
.table-container h2 {
color: #0d8b70;
display: none;
}
.table-container button {
border: none;
background: #13838b;
color: white;
border-radius: 3px;
padding: 5px 7px;
font-size: 18px;
cursor: pointer;
margin: 15px;
}
.table-container button:hover {
opacity: 0.7;
}
.table-container button:focus {
outline: none;
}
/* modal background */
.modal {
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto; /* enable scroll if needed */
background-color: black; /* fallback color */
background-color: rgba(0, 0, 0, 0.6);
}
/* modal content */
.modal-content {
background-color: rgb(240, 240, 240);
color: rgb(32, 32, 32);
font-size: 2em;
font-weight: bold;
/* 16 % from the top and centered */
margin: 16% auto;
padding: 20px;
border: 2px solid black;
border-radius: 10px;
width: 380px;
max-width: 80%;
}
.modal-content p {
margin: 0;
padding: 0;
}
/* close button for modal dialog */
.close {
color: rgb(170, 170, 170);
float: right;
position: relative;
top: -25px;
right: -10px;
font-size: 34px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<!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">
<link rel="stylesheet" href="multiplayer.css">
<title>Document</title>
</head>
<body>
<div class="container-out">
<div class="container-in">
<div class="table-container">
<p>Player <span id="player">X</span> your turn</p>
<table align="center">
<tr>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
</tr>
<tr>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
</tr>
<tr>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
</tr>
</table>
<h2 id="message">Player <span id="winner"></span> Wins</h2>
<button id="reset">Reset</button>
</div>
</div>
</div>
<!-- The dialog for getting feedback from the user -->
<!-- <div id="userFeedback" class="modal"> -->
<!-- Modal content -->
<!-- <div class="modal-content">
<p id="questionText"></p>
<p><button id="yesBtn">Yes</button> <button id="noBtn">No</button></p>
</div>
</div> -->
<!-- The options dialog -->
<div id="optionsDlg" class="modal">
<!-- Modal content -->
<div class="modal-content">
<h3>Alege simbolul:</h3>
<input type="text" id="nume1">
<label><input type="radio" name="player" id="rx" value="x" checked>X (joaca primul) </label>
<label><input type="radio" name="player" id="ro" value="o">O<br></label>
<input type="text" id="nume2">
<p><button id="okBtn" onclick="getOptions()">Play</button></p>
</div>
</div>
</body>
<script src="multiplayer.js"></script>
</html>
That is the singleplayer part.I want to use somehow the same code for the files.
//variabile globale
let x='x';
let o='0';
let player=x;
let computer=o;
let tura=x;
let currentPlayer=x;
function showOptions() {
if (player == o) {
document.getElementById("rx").checked = false;
document.getElementById("ro").checked = true;
}
else if (player == x) {
document.getElementById("rx").checked = true;
document.getElementById("ro").checked = false;
}
document.getElementById("optionsDlg").style.display = "block";
}
function getOptions() {
if (document.getElementById('rx').checked === true) {
player = x;
computer = o;
tura = player;
}
else {
player = o;
computer = x;
tura = computer;
}
document.getElementById("optionsDlg").style.display = "none";
}
function closeModal(id) {
document.getElementById(id).style.display = "none";
}
if(player==x)
{
currentPlayer==player;
}
else{
currentPlayer==computer;
}
//stores the status of the game, whether its over or still in play
let gameStatus = "Game On";
//Gets all Boxes elements
const boxes = document.getElementsByClassName("box");
//loops through all the elements
for (let i = 0; i < boxes.length; i++) {
//adds event listener to each box;
boxes[i].addEventListener("click", function() {
//checks if the box has an x or an o in it and also checks if the game is still on
if (boxes[i].innerHTML.trim() == "" && gameStatus == "Game On") {
//adds x or o for the current play in their choosen box
boxes[i].innerHTML = currentPlayer;
//changes player turns
currentPlayer = currentPlayer == player ? computer : player;
//changes player's turn label on top of the game
if(currentPlayer==player){
document.getElementById(
"player"
).innerHTML = nume1.toUpperCase();}
else{
document.getElementById(
"player"
).innerHTML = nume2.toUpperCase();}
//checks 3 matching x's or o's
if (
boxes[0].innerHTML == boxes[1].innerHTML &&
boxes[1].innerHTML == boxes[2].innerHTML &&
boxes[0].innerHTML.trim() != ""
) {
showWinner(0, 1, 2);
} else if (
boxes[3].innerHTML == boxes[4].innerHTML &&
boxes[4].innerHTML == boxes[5].innerHTML &&
boxes[3].innerHTML.trim() != ""
) {
showWinner(3, 4, 5);
} else if (
boxes[6].innerHTML == boxes[7].innerHTML &&
boxes[7].innerHTML == boxes[8].innerHTML &&
boxes[6].innerHTML.trim() != ""
) {
showWinner(6, 7, 8);
} else if (
boxes[0].innerHTML == boxes[3].innerHTML &&
boxes[3].innerHTML == boxes[6].innerHTML &&
boxes[0].innerHTML.trim() != ""
) {
showWinner(0, 3, 6);
} else if (
boxes[1].innerHTML == boxes[4].innerHTML &&
boxes[4].innerHTML == boxes[7].innerHTML &&
boxes[1].innerHTML.trim() != ""
) {
showWinner(1, 4, 7);
} else if (
boxes[2].innerHTML == boxes[5].innerHTML &&
boxes[5].innerHTML == boxes[8].innerHTML &&
boxes[2].innerHTML.trim() != ""
) {
showWinner(2, 5, 8);
} else if (
boxes[0].innerHTML == boxes[4].innerHTML &&
boxes[4].innerHTML == boxes[8].innerHTML &&
boxes[0].innerHTML.trim() != ""
) {
showWinner(0, 4, 8);
} else if (
boxes[2].innerHTML == boxes[4].innerHTML &&
boxes[4].innerHTML == boxes[6].innerHTML &&
boxes[2].innerHTML.trim() != ""
) {
showWinner(2, 4, 6);
}else if(
(boxes[0].innerHTML != boxes[1].innerHTML!=boxes[2].innerHTML!=
boxes[3].innerHTML!=boxes[4].innerHTML!=boxes[5].innerHTML!=
boxes[6].innerHTML!=boxes[7].innerHTML!=boxes[8].innerHTML)
&&(boxes[0].innerHTML.trim() != "")
&&(boxes[1].innerHTML.trim() != "")
&&(boxes[2].innerHTML.trim() != "")
&&(boxes[3].innerHTML.trim() != "")
&&(boxes[4].innerHTML.trim() != "")
&&(boxes[5].innerHTML.trim() != "")
&&(boxes[6].innerHTML.trim() != "")
&&(boxes[7].innerHTML.trim() != "")
&&(boxes[8].innerHTML.trim() != "")
){
roundDraw();
}
}
});
}
function roundDraw(){
document.getElementById('message').innerHTML=`Match is a tie`;
document.getElementById("message").style.display = "block";
gameStatus="Game Over";
}
//resets the game
document.getElementById("reset").addEventListener("click", function() {
for (let i = 0; i < boxes.length; i++) {
boxes[i].innerHTML = "";
boxes[i].style.backgroundColor = "#dee9ec";
boxes[i].style.color = "black";
}
currentPlayer = "x";
document.getElementById("message").style.display = "none";
document.getElementById("player").innerHTML = "X";
gameStatus = "Game On";
});
//displays the winner
function showWinner(x, y, z) {
let nume1=document.getElementById('nume1').value;
let nume2=document.getElementById('nume2').value;
boxes[x].style.background = "#0d8b70";
boxes[x].style.color = "white";
boxes[y].style.background = "#0d8b70";
boxes[y].style.color = "white";
boxes[z].style.background = "#0d8b70";
boxes[z].style.color = "white";
if(currentPlayer==player){
document.getElementById(
"winner"
).innerHTML = nume2.toUpperCase();}
else{
document.getElementById(
"winner"
).innerHTML = nume1.toUpperCase();}
document.getElementById("message").style.display = "block";
gameStatus = "Game Over";
}
function computerMove(){
}
.container-out {
font-family: "Fira Sans", sans-serif;
padding: 15px 0;
}
.container-in {
width: 97%;
margin: 0 auto;
}
.table-container {
margin: 10 auto;
text-align: center;
}
.box {
min-width: 70px;
min-height: 70px;
background: #dee9ec;
text-align: center;
vertical-align: center;
font-size: 50px;
font-weight: 900;
cursor: pointer;
}
.box:hover {
opacity: 0.7;
}
.table-container h2 {
color: #0d8b70;
display: none;
}
.table-container button {
border: none;
background: #13838b;
color: white;
border-radius: 3px;
padding: 5px 7px;
font-size: 18px;
cursor: pointer;
margin: 15px;
}
.table-container button:hover {
opacity: 0.7;
}
.table-container button:focus {
outline: none;
}
/* modal background */
.modal {
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto; /* enable scroll if needed */
background-color: black; /* fallback color */
background-color: rgba(0, 0, 0, 0.6);
}
/* modal content */
.modal-content {
background-color: rgb(240, 240, 240);
color: rgb(32, 32, 32);
font-size: 2em;
font-weight: bold;
/* 16 % from the top and centered */
margin: 16% auto;
padding: 20px;
border: 2px solid black;
border-radius: 10px;
width: 380px;
max-width: 80%;
}
.modal-content p {
margin: 0;
padding: 0;
}
/* close button for modal dialog */
.close {
color: rgb(170, 170, 170);
float: right;
position: relative;
top: -25px;
right: -10px;
font-size: 34px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<!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">
<link rel="stylesheet" href="singleplayer.css">
<title>Document</title>
</head>
<body>
<div class="container-out">
<div class="container-in">
<div class="table-container">
<p>Player <span id="player">X</span> your turn</p>
<table align="center">
<tr>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
</tr>
<tr>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
</tr>
<tr>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
<td><div class="box"></div></td>
</tr>
</table>
<h2 id="message">Player <span id="winner"></span> Wins</h2>
<button id="reset">Reset</button>
</div>
</div>
</div>
<!-- The dialog for getting feedback from the user -->
<!-- <div id="userFeedback" class="modal"> -->
<!-- Modal content -->
<!-- <div class="modal-content">
<p id="questionText"></p>
<p><button id="yesBtn">Yes</button> <button id="noBtn">No</button></p>
</div>
</div> -->
<!-- The options dialog -->
<div id="optionsDlg" class="modal">
<!-- Modal content -->
<div class="modal-content">
<h3>Alege simbolul:</h3>
<label><input type="radio" name="player" id="rx" value="x" checked>X (joaca primul) </label>
<label><input type="radio" name="player" id="ro" value="o">O<br></label>
<p><button id="okBtn" onclick="getOptions()">Play</button></p>
</div>
</div>
</body>
<script src="singleplayer.js"></script>
</html>
Remove this part:
//changes player turns
currentPlayer = currentPlayer == player ? computer : player;
//changes player's turn label on top of the game
if(currentPlayer==player){
document.getElementById(
"player"
).innerHTML = nume1.toUpperCase();}
else{
document.getElementById(
"player"
).innerHTML = nume2.toUpperCase();}
because the computer will do its turn right after the human so it's unnecessary to show its name.
Replace this code with code of the computer's turn, something like this:
let randomSquare = Math.floor(Math.random() * boxes.length);
if (boxes[randomSquare].innerHTML.trim() === "") {
boxes[randomSquare].innerHTML = computer;
}
Also add:
if (currentPlayer === computer) {
// same code as above
}
below
//Gets all Boxes elements
const boxes = document.getElementsByClassName("box");
for the case that the computer goes first.
I really recommend that instead of only representing the game board in the HTML, you should represent it first in JavaScript (using an array that contains 3 arrays of size 3 for example) and then after each turn converting this representation into HTML. This will make your code much simpler and more readable.

How to stop lag when going through a for loop?

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.

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
});

How to perform a case insensitive string comparison? [duplicate]

This question already has answers here:
How to do case insensitive string comparison?
(23 answers)
Closed 8 years ago.
I have a textbox on my website and the user can input commands. But the thing is the commands are case sensitive. How do I make the commands not case sensitive? Here is my code:
JavaScript:
function showAlert() {
var txtCtrl = document.getElementById("textbox1");
var txtVal = txtCtrl.value;
if (txtVal == '') {
alert('Please fill in the text box. For a list of commands type "Help" into the text box.');
}else if (txtVal == 'Start' || txtVal == 'start') {
alert('Hello. What would you like me to do?');
}else if (txtVal === 'Weather' || txtVal === 'weather') {
window.location = "https://www.google.com/#q=weather";
}else if (txtVal === 'Time' || txtVal === 'time') {
alert('The current time according to your computer is' + formatTime(new Date()));
}else if (txtVal === 'Help' || txtVal === 'help') {
window.location = "help/index.html";
}else if (txtVal === 'Donate' || txtVal === 'donate') {
window.location = "donate/index.html";
}else if (txtVal === 'www.' || txtVal === 'WWW.') {
}else{
alert('Sorry, I do not reconise that command. For a list of commands, type "Help" into the text box.');
}
}
//Show time in 24hour format
function showTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
return [ h, m ].join(':')
}
//Show time in 12hour format
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "PM" : "AM"].join(" ");
}
return formatted;
}
})();
And HTML:
<!doctype html>
<html>
<head>
<title>Random Project</title>
</head>
<style type="text/css">
body {
margin:0;
font-family: arial, sans-serif;
padding-top: 80px;
}
.container {
margin:auto;
text-align:center;
}
.logo {
margin:auto;
width:512px;
text-align:center;
padding-bottom:0px;
}
#textbox1 {
border: 1px solid #ddd;
border-radius: 0px 0px 0px 0px;
width: 512px;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 7px;
padding-right: 7px;
height: 20px;
font-size: 16px;
outline: none;
font-family: arial, sans-serif;
}
#textbox1:focus {
border: 1px solid #0266C8;
}
#button1 {
margin-top: 22px;
padding: 2px 10px 2px 10px;
outline:none;
background-color:#eee;
border:1px solid #ddd;
border-radius:2px;
}
#button1:hover {
background-color: #f5f5f5;
}
#button1:focus {
border: 1px solid #0266C8;
}
#button1_text {
font:bold 11px/27px Arial,sans-serif!important;
color:#333;
}
.information {
font-size:12px;
color:#555;
}
.separator {
height:100px;
}
.tip {
color:green;
font-weight:bold;
font-size:12px;
margin-top:10px;
}
.tip_text {
color:#111;
font-weight:normal;
}
</style>
<body>
<div class="container">
<img class="logo" src="logo.png" width="450" height="110" alt="Random Project">
<input type="text" name="textbox1" value="" spellcheck="false" dir="ltr" placeholder="Type here" id="textbox1"><br>
<button id="button1" name="button1" aria-label="Help me" onClick="showAlert();">
<span id="button1_text">Help me</span>
</button>
<div class="separator"></div>
<span class="information">© Copyright DemDevs 2013. All rights reserved. Made by Omar Latreche<br>Donate now</span>
<div class="tip">
<span class="tip">Tip: </span><span class="tip_text">The commands are NOT case sensitive</span>
</div>
</div>
<div class=""></div>
</body>
</html>
Any help will be greatly appreciated.
Thanks, Omar!
Edit:
I figured it out, I made two new variables:
var txtValUpper = txtVal.toUpperCase();
and
var txtValLower = txtVal.toLowerCase();
then put them into the code for example:
if (txtValUpper == 'start' || txtValLower == 'start')
{
alert('Hello. What would you like me to do?');
}
To case insensitively compare strings, convert them to consistent case first.
if ("Foo".toLowerCase() === "fOo".toLowerCase())
You can convert string to uppercase and compare them
if(txtVal.toUpperCase() === "Donate".toUpperCase())
After this line
var txtVal = txtCtrl.value;
txtVal = txtVal.toLowerCase();

Categories

Resources