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.
I'm working on a tictactoe Person vs Person game. As a bonus, we can try to implement a minimax algorithm to play against the computer. After numerous trials and errors, I think I have the function so far, that it goes through the calculation without an error. However, the return value for best Score is always -10, assuming the player and not the computer would win.
I have two problems in the code:
the minimax-function always returns the value -10, assuming the person would win.
I cant play the last turn. In the debugger I can see that my gameData array, that keeps track of the visible field, works normally like so: [0,"X","X","O","X","O","O",7,"X"]. But the arrays player.person and player.computer have already stored the 0 and the 7. This should not happen.
At this point I am stuck. And I would tell you what I have been trying so far, but the last couple hours were just poking in the dark pretty much. Therefore the least I can do is write down the steps the code takes till the end:
Important variables etc:
Computer is represented by "O", person by "X"
Array gameData: Starts as [0,1,2,...,8] and replaces the numbers with "X" or "O". It tries to prevent that the tictactoe fields can be selected more than once.
Object player with .person-Array and .computer-Array both start as empty. I use these to check if either of them won the game.
isWinner(PLAYER) iterates through the winning conditions and checks if person or computer match it. The function returns the object ({win:true}) if so.
isTie() checks if there is a tie. It returns the object ({tie:true]), if the conditions isWinner(player.computer) = false, isWinner(player.person) = false and emptySpaces(gameData).length = 0 are met.
the function bestMove() searches for the bestMove of computer. Here's where minimax gets executed.
Code Logic overall:
the code starts at line 140 with function vsComputerGame()
next step is function personMove() in line 301
the player's choice "X" gets stored in the gameData Array. EG gameData = [0,"X",2,...,8]. And the position of "X" (in the exp 1`) gets pushed into player.person.
next it checks, if the person won the game or the game is a tie.
next the function bestMove() gets executed. It chooses a tictactoe-field for the computer.
next player.person and player.computer get updated. Without this step, minimax keeps pushing numbers in those arrays.
Code logic bestMove() and minimax():
bestMove() starts at line 190
the initial player.person and player.computer are saved, to restore them, right after the minimax() function returns a value. Same problem as above: Otherwise, isWinner() returns true on the second click of the player.
for loop gets executed. It selects the first available spot in gameData and replaces it with an "O". player.computer gets updated with this possible move from the computer.
then minimax gets executed, which basically has the same code for both player.computer and player.person, as described in this for loop.
when minimax() returns a value, it get stored in the variable score.
now the gameData Array, player.person and player.computer are reset, so the next iteration of the for loop does not flood them.
at last the if (score.eval > bestScore) checks for the highest score. If highest, the index of the current iteration gets stored in the move variable and is then used to place the "O" on the visible field and inside gameData.
"use strict"
// this function stores the chosen players (condition: player1, player2, computer). The start-game is in another module
let menupage = (function() {
let playerSelection = document.querySelectorAll(".player-selection");
let modalContainer = document.querySelector(".modal-bg");
let submitName = document.querySelector("#submit");
let btnColorPlayerTwo = document.querySelector("#player-two");
let btnColorComputer = document.querySelector("#computer");
let btnColorplayerOne = document.querySelector("#player-one");
let modalClose = document.querySelector(".modal-close");
let inputField = document.querySelector("#name");
let isplayerOne;
let gameModeData = {
playerOne : "",
playerTwo : "",
computer : false,
}
function closeModal() {
inputField.value = "";
modalContainer.classList.remove("bg-active");
}
function submitPlayer() {
if (isplayerOne === true) {
if (inputField.value === "") {
alert("Please enter your battle-tag");
} else if (inputField.value !== "") {
btnColorplayerOne.style.backgroundColor = "#4CAF50";
gameModeData.playerOne = inputField.value;
inputField.value = "";
modalContainer.classList.remove("bg-active");
}
}
if (isplayerOne === false) {
if (inputField.value === "") {
alert("Please enter your battle-tag");
} else if (inputField.value !== "") {
gameModeData.playerTwo = inputField.value;
btnColorPlayerTwo.style.backgroundColor = "#f44336";
gameModeData.computer = false;
btnColorComputer.style.backgroundColor = "#e7e7e7";
inputField.value = "";
modalContainer.classList.remove("bg-active");
}
}
}
function definePlayer(id, color) {
modalClose.addEventListener("click", closeModal);
if (id === "player-one") {
if (color.backgroundColor === "" || color.backgroundColor === "rgb(231, 231, 231)") {
isplayerOne = true;
modalContainer.classList.add("bg-active");
submitName.addEventListener("click", submitPlayer);
} else if (color.backgroundColor === "rgb(76, 175, 80)") {
color.backgroundColor = "#e7e7e7";
gameModeData.playerOne = "";
}
}
if (id === "player-two") {
if (color.backgroundColor === "" || color.backgroundColor === "rgb(231, 231, 231)") {
isplayerOne = false;
modalContainer.classList.add("bg-active");
submitName.addEventListener("click", submitPlayer);
}
}
}
function defineOponent(target) {
if (target.backgroundColor === "rgb(0, 140, 186)") {
return;
} else if (target.backgroundColor === "rgb(231, 231, 231)" || target.backgroundColor === "") {
target.backgroundColor = "#008CBA";
btnColorPlayerTwo.style.backgroundColor = "#e7e7e7";
gameModeData.playerTwo = "";
gameModeData.computer = true;
}
}
let setupPlayers = function setupPlayers() {
if (this.id === "player-one" || this.id === "player-two") {
definePlayer(this.id, this.style);
} else if (this.id === "computer") {
defineOponent(this.style);
}
}
playerSelection.forEach(button => button.addEventListener("click", setupPlayers))
return gameModeData;
}())
let startRound = (function startRound() {
let startGameBtn = document.querySelector("#start-game");
let startScreen = document.querySelector(".start-screen");
let gameboard = document.querySelector(".gameboard");
let selectionMenu = document.querySelector(".window-container");
let frame = document.querySelector(".frame");
let scoreboardPlayer = document.querySelector(".scoreboard-left");
let scoreboardOponent = document.querySelector(".scoreboard-right");
let scorePlayer = document.querySelector(".scoreboard-player");
let scoreOponent = document.querySelector(".scoreboard-oponent");
function displayScore() {
scorePlayer.innerText = menupage.playerOne;
menupage.computer === false ? scoreOponent.innerText = menupage.playerTwo : scoreOponent.innerText = "Computer";
}
function startGame() {
if (menupage.playerOne === "") {
alert("Please choose your profile.");
} else if (menupage.playerTwo === "" && menupage.computer === false) {
alert("Please choose an opponent.")
} else {
startScreen.style.display = "none";
gameboard.style.display = "grid";
scoreboardPlayer.style.display = "grid";
scoreboardOponent.style.display = "grid";
frame.style.display = "none";
selectionMenu.style.gridTemplateAreas = '"header header header" "scoreboard-left gameboard scoreboard-right" "frame frame frame"';
displayScore();
game();
}
}
startGameBtn.addEventListener("click", startGame);
}())
/* ***************************** GAME VS COMPUTER FUNCTION STARTS HERE ************************* */
let vsComputerGame = (function vsComputerGame() {
let player = {
person : [],
computer : [],
}
let gameData = [0, 1, 2, 3, 4, 5, 6, 7, 8]
let isWinner = function isWinner(PLAYER) {
let check = PLAYER.join();
let condition = {
1 : ["0","1","2"],
2 : ["3","4","5"],
3 : ["6","7","8"],
4 : ["0","4","8"],
5 : ["2","4","6"],
6 : ["0","3","6"],
7 : ["1","4","7"],
9 : ["2","5","8"]
}
for (const property in condition) {
if (condition[property].every(v => check.includes(v)) === true) {
return ({win : true});
}
}
return ({win : false });
};
let isTie = function isTie() {
if (emptySpaces(gameData).length === 0 && isWinner(player.computer).win === false && isWinner(player.person).win === false) {
return ({tie: true});
} else {
return ({tie : false});
}
}
function emptySpaces(gameData) {
let updatedBoard = [];
for (let i = 0; i < gameData.length; i++) {
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
updatedBoard.push(gameData[i]);
}
}
}
return updatedBoard;
}
function bestMove() {
let bestScore = -Infinity;
let move;
// the object player with the values {player:[], computer:[]} is used in isWinner to check who won,
// storedComputer and storedPlayer is needed, to reset both arrays after they go through minimax,
// without, the two object-arrays get fludded
let storedComputer = player.computer.map(x => x);
let storedPlayer = player.person.map(x => x);
// first round of the for loop sets a field for the computer,
// first execution of minimax jumps to player.person
for (let i = 0; i < 9; i++) {
// gameData is the Array, that stores the players' moves. Example: [0, 1, 2, "X", 4, 5, "O", 7, 8]
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
gameData[i] = "O";
player.computer.push(i);
let score = minimax(gameData, player.person);
gameData[i] = i;
player.person = storedPlayer;
player.computer = storedComputer;
if (score.eval > bestScore) {
bestScore = score.eval;
move = i;
console.log(bestScore);
}
}
}
}
// after a move is found for the computer, O gets logged in the gameData Array and on the visible gameboard
let positionO = document.getElementsByName(move);
gameData[move] = "O";
positionO[0].innerText = "O";
}
function minimax(gameData, PLAYER) {
// the BASE of minimax.
// ************ console.log shows, that it always returns -10 ***************
if (isWinner(player.person).win === true) { return ({eval:-10});}
if (isWinner(player.computer).win === true) { return ({eval:10});}
if (isTie().tie === true) {return ({eval:0});};
/*
PLAYER.push pushes the index-number into either player.computer or player.person
This is needed to check the isWinner function
After that, these Arrays get stored in storedComputer and storedPlayer
*/
if (PLAYER === player.computer) {
let bestScore = -Infinity;
for (let i = 0; i < 9; i++) {
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
PLAYER.push(i);
//let storedComputer = player.computer.map(x => x);
//let storedPlayer = player.person.map(x => x);
gameData[i] = "O";
let score = minimax(gameData, player.person);
//player.person, player.computer and gameData are resetted, after minimax returns a value
gameData[i] = i;
//player.person = storedPlayer;
//player.computer = storedComputer;
if (score.eval > bestScore) {
bestScore = score.eval;
}
}
}
}
return bestScore;
} else {
let bestScore = Infinity;
for (let i = 0; i < 9; i++) {
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
PLAYER.push(i);
//let storedComputer = player.computer.map(x => x);
//let storedPlayer = player.person.map(x => x);
gameData[i] = "X";
let score = minimax(gameData, player.computer);
//player.person = storedPlayer;
//player.computer = storedComputer;
gameData[i] = i;
if (score.eval < bestScore) {
bestScore = score.eval;
}
}
}
}
return bestScore;
}
}
let cells = document.querySelectorAll(".cell");
cells.forEach(cell => cell.addEventListener("click", personMove));
function personMove() {
if (this.innerText === "X" || this.innerText === "O") {
return;
} else {
let playersChoice = this.getAttribute("data-parent");
player.person.push(Number(this.getAttribute("data-parent")));
this.innerText = "X";
gameData[playersChoice] = "X";
if (isWinner(player.person).win === true) {
console.log("Win");
};
isTie();
bestMove();
player.computer = [];
player.person = [];
for (let i = 0; i < 9; i++) {
if (gameData[i] === "X") {
player.person.push(i);
} else if (gameData[i] === "O") {
player.computer.push(i);
}
}
}
}
})
/* ***************************** GAME VS COMPUTER FUNCTION ENDS HERE ************************* */
let vsPersonGame = (function vsPersonGame() {
let i = 1;
let player = [];
let oponent = [];
let buttons = document.querySelectorAll(".cell");
buttons.forEach(button => button.addEventListener("click", selection));
function selection() {
let newLocal = this
storeSelection(newLocal);
checkWinner();
}
function storeSelection(input) {
if (i >= 10 || input.innerText !== "") {
return;
} else if (i % 2 === 0) {
return input.innerText = "O", oponent.push(input.dataset.parent),
i++;
} else if (i % 2 !== 0) {
return input.innerText = "X", player.push(input.dataset.parent),
i++;
}
}
function checkWinner() {
let condition = {
1 : ["0","1","2"],
2 : ["3","4","5"],
3 : ["6","7","8"],
4 : ["0","4","8"],
5 : ["2","4","6"],
6 : ["0","3","6"],
7 : ["1","4","7"],
9 : ["2","5","8"]
}
for (const property in condition) {
let toStringplayer = player.join();
let toStringoponent = oponent.join();
if (condition[property].every(v => toStringplayer.includes(v)) === true) {
return alert(menupage.playerOne + " won");
} else if (condition[property].every(v => toStringoponent.includes(v)) === true) {
return alert(menupage.playerTwo + " won");
} else if (i === 10) {
if (condition[property].every(v => toStringplayer.includes(v)) === true) {
return alert(menupage.playerOne + " won");
} else if (condition[property].every(v => toStringoponent.includes(v)) === true) {
return alert(menupage.playerTwo + " won");
} else {
return alert("You tied");
}
}
}
}
})
let game = (function() {
if (menupage.computer === true) {
vsComputerGame();
} else {
vsPersonGame();
}
});
html, body {
display: grid;
height: 100%;
margin: 0;
padding: 0;
}
.window-container {
display: grid;
height: 100%;
grid-template-rows: 10% 80% 10%;
grid-template-areas:
"header header header"
". start-screen ."
"frame frame frame";
}
.header {
grid-area: header;
margin-top: 50px;
font-size: 30px;
text-align: center;
color: red;
font-weight: bolder;
}
.start-screen {
grid-area: start-screen;
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 30%;
}
.selection-menu {
flex: 1;
display: grid;
grid-template-rows: 40% 20% 40%;
grid-template-areas:
". . player-two"
"player-one vs ."
". . computer"
}
#player-one {
grid-area: player-one;
background-color: #e7e7e7;
}
#player-two {
grid-area: player-two;
background-color: #e7e7e7;
}
#computer {
grid-area: computer;
background-color: #e7e7e7;
}
#start-game {
display: flex;
cursor: pointer;
border: none;
color: white;
background-color: rgb(37, 36, 36);
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
#vs {
grid-area: vs;
text-align: center;
font-size: 30px;
font-weight: bold;
color: #4CAF50;
}
.player-selection {
cursor: pointer;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.gameboard {
grid-area: gameboard;
margin-top: 10%;
display: none;
justify-content: center;
grid-template-rows: 150px 150px 150px;
grid-template-columns: 150px 150px 150px;
grid-template-areas:
"tL tM tR"
"mL mM mR"
"bL bM bR";
}
.frame {
grid-area: frame;
display: flex;
position: fixed;
height: 250px;
bottom: 0px;
left: 0px;
right: 0px;
margin-bottom: 0px;
justify-content: center;
align-items: center;
}
.cell {
display: flex;
justify-content: center;
align-items: center;
font-size: 40px;
cursor: pointer;
}
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#tL {
grid-area: tL;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#tM {
grid-area: tM;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#tR {
grid-area: tR;
border-bottom: 2px solid black;
}
#mL {
grid-area: mL;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#mM {
grid-area: mM;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#mR {
grid-area: mR;
border-bottom: 2px solid black;
}
#bL {
grid-area: bL;
border-right: 2px solid black;
}
#bM {
grid-area: bM;
border-right: 2px solid black;
}
#bR {
grid-area: bR;
}
.modal-bg {
position: fixed;
width: 100%;
height: 100vh;
top: 0;
left: 0;
background-color: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.5s;
}
.bg-active {
visibility: visible;
opacity: 1;
}
.modal {
position: relative;
background-color: white;
border-radius: 5px 5px 5px 5px;
width: 30%;
height: 20%;
display: flex;
justify-content: space-around;
align-items: center;
flex-direction: column;
}
.modal button {
padding: 10px 50px;
background-color: #2980b9;
color: white;
border: none;
cursor: pointer;
}
.modal-close {
position: absolute;
top: 10px;
right: 10px;
font-weight: bold;
cursor: pointer;
}
#modal-headline {
font-size: 20px;
}
#submit {
margin-top: 5px;
}
.scoreboard-left {
display: none;
}
.scoreboard-player {
grid-area: scoreboard-player;
display: flex;
}
.scoreboard-right {
display: none;
}
.scoreboard-oponent {
grid-area: scoreboard-oponent;
display: flex;
}
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link href="styles.css" rel="stylesheet" type="text/css" />
<script src="script.js" defer></script>
<title>Tic Tac Toe</title>
</head>
<body>
<div class="window-container">
<div class="header">Tic Tac Toe</div>
<div class="start-screen">
<div class="selection-menu">
<button class="player-selection" id="player-one">Player One</button>
<button class="player-selection" id="player-two">Player Two</button>
<div id="vs">vs</div>
<button class="player-selection" id="computer">Computer</button>
</div>
</div>
<div class="gameboard">
<div class="cell unselectable" id="tL" data-parent="0" name="0"></div>
<div class="cell unselectable" id="tM" data-parent="1" name="1"></div>
<div class="cell unselectable" id="tR" data-parent="2" name="2"></div>
<div class="cell unselectable" id="mL" data-parent="3" name="3"></div>
<div class="cell unselectable" id="mM" data-parent="4" name="4"></div>
<div class="cell unselectable" id="mR" data-parent="5" name="5"></div>
<div class="cell unselectable" id="bL" data-parent="6" name="6"></div>
<div class="cell unselectable" id="bM" data-parent="7" name="7"></div>
<div class="cell unselectable" id="bR" data-parent="8" name="8"></div>
</div>
<div class="modal-bg">
<div class="modal">
<h2 id="modal-headline">Choose a Name:</h2>
<input type="text" id="name">
<button id="submit" class="submit">Submit</button>
<span class="modal-close">X</span>
</div>
</div>
<div class="frame">
<button id="start-game">Start Game</button>
</div>
<div class="scoreboard-left">
<div class="display-player">
<div class="scoreboard-player"></div>
<div class="p-win">Wins: </div><div class="player-win">0</div>
<div class="p-loss">Losses: </div><div class="player-loss">0</div>
<div class="p-tie">Ties: </div><div class="player-tie">0</div>
</div>
</div>
<div class="scoreboard-right">
<div class="display-oponent">
<div class="scoreboard-oponent"></div>
<div class="o-win">Wins: </div><div class="oponent-win">0</div>
<div class="o-loss">Losses: </div><div class="oponent-loss">0</div>
<div class="o-tie">Ties: </div><div class="oponent-tie">0</div>
</div>
</div>
</div>
</body>
</html>
I appreciate any feedback and hints to solve the problem.
function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
// var last2 = 100 - integer2;
if (symbolCount >= 100) {
document.querySelector('.hidden_block').style.color = 'green';
}
else if (symbolCount <= 100) {
document.querySelector('.hidden_block').style.color = 'black';
document.querySelector('.error').style.display = "block";
}
else {
document.getElementById('max').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
email.addEventListener("click", function(){
document.querySelector('.hidden_block').style.display = 'block';
document.getElementById('max').style.display = 'none';
});
#max, #max2 {
text-align: right;
margin-right: 55px;
}
.hidden_block {
display: none;
text-align: right;
margin-right: 55px;
}
.error {
display: none;
color: red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<label for="email">Positive</label>
<textarea type="email" class="form-control" id="email" oninput="someFunc()" placeholder="Tell people about your experience: describe the place or activity, recommendations for travelers?"></textarea>
<p id="max">Minimal length - symbols</p>
<div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (minimum:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long. Adding details really helps travelers.</span>
Hi everyone.I have a that simple textarea field.I need to realize something like that.When u write less than 100 words and click the outside of the email id the border color must be red.And error class must displayed.And i need to if the textarea field is empty the tag p with id max must be display block if the user will write any symbol the id max must bu display none.Thanks for help
function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
var integerValue = document.getElementById('email');
var hidden_block = document.querySelector('.hidden_block');
var max = document.getElementById('max');
var error = document.querySelector('.error');
var positive = document.getElementById("positive");
// var last2 = 100 - integer2;
if (integer >= 1) {
hidden_block.style.display = 'inline-block';
max.style.display = 'none';
integerValue.classList.add("form-control");
} else {
hidden_block.style.display = 'none';
max.style.display = 'block';
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
}
integerValue.addEventListener("click", function(){
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
});
//Red error and border
document.body.addEventListener("click", function(e) {
var target = e.target || e.srcElement;
if (target !== integerValue && !isChildOf(target, integerValue)) {
error.style.display = "inline-block";
integerValue.classList.add("form-redBorder");
positive.style.color = "red";
} if (integer >= 100) {
error.style.display = "none";
integerValue.classList.remove("form-redBorder");
positive.style.color = "#002C38";
}
}, false);
function isChildOf(child, parent) {
if (child.parentNode === parent) {
return true;
} else if (child.parentNode === null) {
return false;
} else {
return isChildOf(child.parentNode, parent);
}
}
//Finished Red error and border
//Start to count symbols
if (symbolCount >= 100) {
hidden_block.style.color = 'green';
}
else if (symbolCount <= 100) {
hidden_block.style.color = 'black';
}
else {
max.style.color = 'black';
// document.getElementById('max2').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
#email {
display: block;
padding: 6px 12px;
margin: 0 auto;
width: 90% !important;
height: 120px !important;
/*border:1px solid #44A1B7 !important;*/
}
.form-control {
margin: 0 auto;
width: 90% !important;
height: 120px !important;
border:1px solid #44A1B7;
}
#positive, #negative {
padding: 14px 15px 1px 55px;
color: #002C38;
font-size: 18px;
}
.form-redBorder {
margin: 0 auto;
border:1px solid #FF0000 !important;
}
#max, #max2 {
position: absolute;
right: 1%;
margin-right: 55px;
}
.hidden_block {
position: absolute;
right: 1%;
display: none;
text-align: right;
margin-right: 55px;
}
.error {
margin-left: 55px;
display: none;
color: #FF0000;
}
<form role="form">
<div class="form-group">
<p class="help-block">About youre site.</p>
<label for="email" id="positive">Positive</label>
<textarea type="email" id="email" oninput="someFunc()" placeholder="Your review must be at least 100 characters long<br> Adding details really helps travelers"></textarea>
<p id="max">(100 character minimum)</p><div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (min:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long.<br> Adding details really helps travelers..</span>
</div>
</form>
I would like to know if there's any way to add images to the arrays of my Slot machine? Right now i've just been able to add numbers in the array.
So far i got this, i know there's only one choice in my array, it's on purpose:
var arr = ["#7.png"];
// var arr = [5];
var credits = 10;
function freezeCheck() {
if (document.getElementById("hold1").checked == true || document.getElementById("hold2").checked == true || document.getElementById("hold3").checked == true) {
// if any is checked, freeze hold buttons.
document.getElementById("hold1").checked = false;
document.getElementById("hold2").checked = false;
document.getElementById("hold3").checked = false;
document.getElementById("hold1").disabled = true;
document.getElementById("hold2").disabled = true;
document.getElementById("hold3").disabled = true;
} else if (document.getElementById("hold1").disabled == true) {
// if any diabled, enable (unfreeze) all hold buttons.
document.getElementById("hold1").disabled = false;
document.getElementById("hold2").disabled = false;
document.getElementById("hold3").disabled = false;
document.getElementById("reel1").classList.remove('hold');
document.getElementById("reel2").classList.remove('hold');
document.getElementById("reel3").classList.remove('hold');
}
};
function getNumbers() {
if(document.getElementById("hold1").checked == false){
document.getElementById("reel1").innerHTML = arr[Math.floor(Math.random() * arr.length)];
} if (document.getElementById("hold2").checked == false){
document.getElementById("reel2").innerHTML = arr[Math.floor(Math.random() * arr.length)];
} if (document.getElementById("hold3").checked == false){
document.getElementById("reel3").innerHTML = arr[Math.floor(Math.random() * arr.length)];
}
updateScore();
insertCoins();
};
function calculateScore() {
document.getElementById('credits').innerHTML = credits;
}
// Win, three alike.
function updateScore() {
if(document.getElementById("reel1").textContent == document.getElementById("reel2").textContent && document.getElementById("reel1").textContent == document.getElementById("reel3").textContent){
credits += document.getElementById("reel1").textContent * 10;
} else if("reel1" != "reel2"){
credits -= 2;
}
};
function insertCoins() {
if (credits <1){
document.getElementById("spin").disabled = true;
}
};
function freezeReel(num) {
if (document.getElementById('hold'+num).checked == true) {
// Unfreeze reel
document.getElementById("hold"+num).checked = false;
document.getElementById("reel"+num).classList.remove('hold');
} else {
// Freeze reel:
document.getElementById("hold"+num).checked = true;
document.getElementById("reel"+num).classList.add('hold');
}
}
* {
margin: 0;
padding: 0;
}
.marginauto {
margin: 0 auto;
}
.button-wrapper {
text-align: center;
margin-top: 15%;
}
.hold-wrapper {
text-align: center;
margin: 10px;
font-size: 48px;
}
.holdbutton {
width: 140px;
height: 200px;
visibility: hidden;
}
.credits {
width: 250px;
height: 100px;
margin: 0 auto;
text-align: center;
}
.reel-wrapper {
width: 1280px;
text-align: center;
margin-top: 10px;
background-color: #ffffff;
}
.button {
background-color: white;
}
.reels {
background-color: #ffffff;
display: inline-block;
font-size: 48px;
text-align: center;
width: 150px;
height: 200px;
border: 1px solid black;
border-radius: 2px;
}
.reels.hold {
border-color: blue;
background: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> </title>
</head>
<body>
<header></header>
<div class="button-wrapper">
<input id="spin" type="button" onClick="getNumbers(); freezeCheck(); calculateScore();" value="Spin" />
</div>
<div class="reel-wrapper marginauto">
<div id="reel1" onClick="freezeReel(1);" class="reels"></div>
<div id="reel2" onClick="freezeReel(2);" class="reels"></div>
<div id="reel3" onClick="freezeReel(3);" class="reels"></div>
</div>
<div class="hold-wrapper">
<input id="hold1" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold2" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold3" type="checkbox" value="Hold" class="holdbutton" />
</div>
<div class="credits">Your Credits: <span id="credits"></span></div>
<script src="script.js"></script>
</body>
</html>
You should use the backgroundImage javascript property and provide value with a source from the array arr.
Refer code:
var arr = ['image1.png', 'image2.png', 'image3.png'];
var credits = 10;
function freezeCheck() {
if (document.getElementById("hold1").checked == true || document.getElementById("hold2").checked == true || document.getElementById("hold3").checked == true) {
// if any is checked, freeze hold buttons.
document.getElementById("hold1").checked = false;
document.getElementById("hold2").checked = false;
document.getElementById("hold3").checked = false;
document.getElementById("hold1").disabled = true;
document.getElementById("hold2").disabled = true;
document.getElementById("hold3").disabled = true;
} else if (document.getElementById("hold1").disabled == true) {
// if any diabled, enable (unfreeze) all hold buttons.
document.getElementById("hold1").disabled = false;
document.getElementById("hold2").disabled = false;
document.getElementById("hold3").disabled = false;
document.getElementById("reel1").classList.remove('hold');
document.getElementById("reel2").classList.remove('hold');
document.getElementById("reel3").classList.remove('hold');
}
};
function getNumbers() {
if(document.getElementById("hold1").checked == false){
document.getElementById("reel1").backgroundImage = "url(" + arr[0] + ")";
} if (document.getElementById("hold2").checked == false){
document.getElementById("reel2").backgroundImage = "url(" + arr[1] + ")";
} if (document.getElementById("hold3").checked == false){
document.getElementById("reel3").backgroundImage = "url(" + arr[2] + ")";
}
updateScore();
insertCoins();
};
function calculateScore() {
document.getElementById('credits').innerHTML = credits;
}
// Win, three alike.
function updateScore() {
if(document.getElementById("reel1").textContent == document.getElementById("reel2").textContent && document.getElementById("reel1").textContent == document.getElementById("reel3").textContent){
credits += document.getElementById("reel1").textContent * 10;
} else if("reel1" != "reel2"){
credits -= 2;
}
};
function insertCoins() {
if (credits <1){
document.getElementById("spin").disabled = true;
}
};
function freezeReel(num) {
if (document.getElementById('hold'+num).checked == true) {
// Unfreeze reel
document.getElementById("hold"+num).checked = false;
document.getElementById("reel"+num).classList.remove('hold');
} else {
// Freeze reel:
document.getElementById("hold"+num).checked = true;
document.getElementById("reel"+num).classList.add('hold');
}
}
* {
margin: 0;
padding: 0;
}
.marginauto {
margin: 0 auto;
}
.button-wrapper {
text-align: center;
margin-top: 15%;
}
.hold-wrapper {
text-align: center;
margin: 10px;
font-size: 48px;
}
.holdbutton {
width: 140px;
height: 200px;
visibility: hidden;
}
.credits {
width: 250px;
height: 100px;
margin: 0 auto;
text-align: center;
}
.reel-wrapper {
width: 1280px;
text-align: center;
margin-top: 10px;
background-color: #ffffff;
}
.button {
background-color: white;
}
.reels {
background-color: #ffffff;
display: inline-block;
font-size: 48px;
text-align: center;
width: 150px;
height: 200px;
border: 1px solid black;
border-radius: 2px;
}
.reels.hold {
border-color: blue;
background: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> </title>
</head>
<body>
<header></header>
<div class="button-wrapper">
<input id="spin" type="button" onClick="getNumbers(); freezeCheck(); calculateScore();" value="Spin" />
</div>
<div class="reel-wrapper marginauto">
<div id="reel1" onClick="freezeReel(1);" class="reels"></div>
<div id="reel2" onClick="freezeReel(2);" class="reels"></div>
<div id="reel3" onClick="freezeReel(3);" class="reels"></div>
</div>
<div class="hold-wrapper">
<input id="hold1" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold2" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold3" type="checkbox" value="Hold" class="holdbutton" />
</div>
<div class="credits">Your Credits: <span id="credits"></span></div>
<script src="script.js"></script>
</body>
</html>
innerHTML stands for standard font in your page and it will only shows text. Since in your array, the value of it is #7.png and it will only display #7.png.
Adding the following code will create img tag in your html code with the images being random.
var elem = document.createElement("img");
elem.setAttribute("src", arr[Math.floor(Math.random() * arr.length)]);
elem.setAttribute("alt", "Slotimg");
document.getElementById("reel1").appendChild(elem);
However if you can create a default image, i would suggest you just add a Img tag in your div, and just change the src attribute by src code, it is going to be much easier and effiecnt
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.