I get a problem when I try generate table in modal with data from js code.
There is a problem with 249 line in js. I can not understand why my params.progress array is not defined.
rock-paper-scissors app on codepen
I create new object in empty params.progress array after every player move:
var objectResults = {
number: params.numberOfRounds,
playerMove: userChoice,
computerMove: computerChoice,
gameResult: params.userScore+":"+params.computerScore,
}
params.progress[params.numberOfRounds] = objectResults;
Finally I try to generate table with those data:
function makeTableFromProgress() {
var resultsTableBody = document.querySelector('#resultsTableBody');
var rows = params.progress.length;
for (i = 0; i<rows; i++) {
var row = resultsTableBody.insertRow(i);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = params.progress[i]['number'];
cell2.innerHTML = params.progress[i]['playerMove'];
cell3.innerHTML = params.progress[i]['computerMove'];
cell4.innerHTML = params.progress[i]['gameResult'];
}
}
In modal window, like this:
<table>
<thead>
<tr>
<th>No.</th>
<th>Player move</th>
<th>Computer move</th>
<th>Game result</th>
</tr>
</thead>
<tbody id="resultsTableBody"></tbody>
</table>
And it brings kind of that problem:
Cannot read property 'number' of undefined
Thanks for help
The problem is in function makeTableFromProgress. i must start with 1 instead of 0 and also insertRow(i - 1); instead of insertRow(i);
function makeTableFromProgress() {
var resultsTableBody = document.querySelector('#resultsTableBody');
var rows = params.progress.length;
for (i = 1; i < rows; i++) {
var row = resultsTableBody.insertRow(i - 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = params.progress[i]['number'];
cell2.innerHTML = params.progress[i]['playerMove'];
cell3.innerHTML = params.progress[i]['computerMove'];
cell4.innerHTML = params.progress[i]['gameResult'];
}
};
The final code will be this
var userScore_span = document.getElementById("user-score");
var computerScore_span = document.getElementById("computer-score");
var scoreBoard_div = document.querySelector(".score-board");
var result_p = document.querySelector(".result > p");
var moveButtons = document.querySelectorAll("[data-move]");
var newGame_div = document.querySelector(".newGame");
var choices_div = document.querySelector(".choices");
var message_p = document.getElementById("message");
var trophy_p = document.getElementById("numberOfWins");
var roundsCounter_p = document.getElementById("numberOfRounds");
var modal_h = document.getElementById("endMessage");
var userName_div = document.getElementById("user-label");
var userName;
var numberOfGames;
var params = {
userScore: 0,
computerScore: 0,
numberOfRounds: 0,
progress: []
}
function main() {
moveButtons.forEach(function(button) {
var userChoice = button.dataset.move;
button.addEventListener('click', function() {
game(userChoice);
});
});
}
function game(userChoice) {
var computerChoice = getComputerChoice();
switch (userChoice + computerChoice) {
case "RockRock":
case "PaperPaper":
case "ScissorsScissors":
draw(userChoice, computerChoice);
break;
case "RockScissors":
case "PaperRock":
case "ScissorsPaper":
win(userChoice, computerChoice);
break;
case "RockPaper":
case "PaperScissors":
case "ScissorsRock":
lose(userChoice, computerChoice);
break;
}
}
function getComputerChoice() {
var choices = ['Rock', 'Paper', 'Scissors'];
randomNumber = Math.floor(Math.random() * 3)
return choices[randomNumber];
}
function draw(userChoice, computerChoice) {
params.numberOfRounds++;
roundsCounter_p.innerHTML = "Number of rounds: " + params.numberOfRounds;
computerScore_span.innerHTML = params.computerScore;
userScore_span.innerHTML = params.userScore;
var smallerUserWord = "user ".fontsize(4);
var smallerCompWord = " comp".fontsize(4);
result_p.innerHTML = smallerUserWord + userChoice + " vs " + computerChoice + smallerCompWord + "<br>It is a draw!";
document.getElementById(userChoice).classList.add('gray-glow');
setTimeout(function() {
document.getElementById(userChoice).classList.remove('gray-glow')
}, 400);
var objectResults = {
number: params.numberOfRounds,
playerMove: userChoice,
computerMove: computerChoice,
gameResult: params.userScore + ":" + params.computerScore,
}
params.progress[params.numberOfRounds] = objectResults;
}
function win(userChoice, computerChoice) {
params.numberOfRounds++;
roundsCounter_p.innerHTML = "Number of rounds: " + params.numberOfRounds;
params.userScore++;
userScore_span.innerHTML = params.userScore;
computerScore_span.innerHTML = params.computerScore;
var smallerUserWord = "user ".fontsize(4);
var smallerCompWord = " comp".fontsize(4);
result_p.innerHTML = smallerUserWord + userChoice + " vs " + computerChoice + smallerCompWord + "<br>You won!";
document.getElementById(userChoice).classList.add('green-glow');
setTimeout(function() {
document.getElementById(userChoice).classList.remove('green-glow')
}, 400);
var objectResults = {
number: params.numberOfRounds,
playerMove: userChoice,
computerMove: computerChoice,
gameResult: params.userScore + ":" + params.computerScore,
}
params.progress[params.numberOfRounds] = objectResults;
endGame();
}
function lose(userChoice, computerChoice) {
params.numberOfRounds++;
roundsCounter_p.innerHTML = "Number of rounds: " + params.numberOfRounds;
params.computerScore++;
computerScore_span.innerHTML = params.computerScore;
userScore_span.innerHTML = params.userScore;
var smallerUserWord = "user ".fontsize(4);
var smallerCompWord = " comp".fontsize(4);
result_p.innerHTML = smallerUserWord + userChoice + " vs " + computerChoice + smallerCompWord + "<br>You lost!";
document.getElementById(userChoice).classList.add('red-glow');
setTimeout(function() {
document.getElementById(userChoice).classList.remove('red-glow')
}, 400);
var objectResults = {
number: params.numberOfRounds,
playerMove: userChoice,
computerMove: computerChoice,
gameResult: params.userScore + ":" + params.computerScore,
}
params.progress[params.numberOfRounds] = objectResults;
endGame();
}
function newGame() {
newGame_div.addEventListener('click', function() {
howManyWins();
})
main();
}
function howManyWins() {
var userAnswer = prompt("TILL HOW MANY WINS?");
if (userAnswer === null || userAnswer === "" || isNaN(userAnswer)) {
thereIsAnError();
} else {
giveMeYourName();
resetScore();
games(userAnswer);
}
}
function thereIsAnError() {
message_p.innerHTML = "Please press NEW GAME and choose the number!";
setTimeout(function() {
message_p.innerHTML = ""
}, 3000);
}
function giveMeYourName() {
var name = prompt("WHAT IS YOUR NAME?");
if (name === null || name === "" || isNaN(name) === false) {
thereIsAnError();
document.querySelector('#trophy').classList.add('trophydisabled');
} else if (name.length > 9) {
message_p.innerHTML = "Your name is too long. 9 letters summary!";
} else {
document.querySelector('#trophy').classList.remove('trophydisabled');
choices_div.classList.remove('choices-disabled');
newGame_div.classList.add('newGame-disabled');
userName_div.innerHTML = name;
userName = name;
}
}
function resetScore() {
params.userScore = 0;
params.computerScore = 0;
params.numberOfRounds = 0;
userScore_span.innerHTML = params.userScore;
computerScore_span.innerHTML = params.computerScore;
roundsCounter_p.innerHTML = "";
}
function games(userAnswer) {
trophy_p.innerHTML = "Up to: " + userAnswer;
numberOfGames = userAnswer;
}
function endGame() {
if (numberOfGames == params.userScore) {
choices_div.classList.add('choices-disabled');
newGame_div.classList.remove('newGame-disabled');
result_p.innerHTML = "";
userName_h = userName;
modal_h.innerHTML = userName + "<br>You won the ENTIRE game!";
makeTableFromProgress()
showModal();
} else if (numberOfGames == params.computerScore) {
choices_div.classList.add('choices-disabled');
newGame_div.classList.remove('newGame-disabled');
showModal();
result_p.innerHTML = "";
userName_h = userName;
modal_h.innerHTML = userName + "<br>You lose the ENTIRE game!";
makeTableFromProgress()
showModal();
}
}
newGame();
choices_div.classList.add('choices-disabled');
//MODAL
var modal = document.getElementById("modal-one");
var showModal = function() {
event.preventDefault();
document.querySelector('#modal-overlay').classList.add('show');
modal.classList.add('show');
};
var hideModal = function(event) {
event.preventDefault();
document.querySelector('#modal-overlay').classList.remove('show');
this.parentElement.classList.remove('show');
};
var closeButtons = document.querySelectorAll('.close');
for (var i = 0; i < closeButtons.length; i++) {
closeButtons[i].addEventListener('click', hideModal);
}
document.querySelector('#modal-overlay').addEventListener('click', hideModal);
var modals = document.querySelectorAll('.modal');
for (var i = 0; i < modals.length; i++) {
modals[i].addEventListener('click', function(event) {
event.stopPropagation();
});
}
function makeTableFromProgress() {
var resultsTableBody = document.querySelector('#resultsTableBody');
var rows = params.progress.length;
for (i = 1; i < rows; i++) {
var row = resultsTableBody.insertRow(i - 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = params.progress[i]['number'];
cell2.innerHTML = params.progress[i]['playerMove'];
cell3.innerHTML = params.progress[i]['computerMove'];
cell4.innerHTML = params.progress[i]['gameResult'];
}
};
$black: #000;
$white: #fff;
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Open Sans', sans-serif;
background-color: #2d3030;
}
header {
background-color: $white;
padding: 20px;
}
header>h1 {
color: #2d3030;
text-align: center;
text-transform: uppercase;
}
#trophy {
margin-top: 20px;
text-align: center;
font-size: 30px;
color: $white;
&.trophydisabled {
display: none;
}
}
#trophy>p {
color: $white;
font-size: 20px;
}
.roundsCounter {
margin-top: 20px;
text-align: center;
}
.roundsCounter>p {
color: $white;
font-size: 20px;
}
.score-board {
margin: 30px auto;
border: 3px solid $white;
border-radius: 5px;
width: 200px;
color: $white;
font-size: 50px;
text-align: center;
padding: 15px 20px;
position: relative;
}
.badge {
width: 100px;
background-color: #af0e0e;
color: $white;
font-size: 15px;
padding: 2px 10px;
text-transform: lowercase;
}
#user-label {
position: absolute;
top: 40px;
left: -110px;
}
#computer-label {
position: absolute;
top: 40px;
right: -110px;
}
.result {
font-size: 40px;
color: $white;
}
.result>p {
text-align: center;
}
.newGame {
margin: 20px auto;
width: 250px;
border: 4px solid $white;
}
.newGame>p {
padding: 10px;
color: $white;
text-align: center;
font-size: 40px;
text-transform: uppercase;
}
.newGame:hover p {
background-color: $white;
color: #d01115;
font-weight: bold;
cursor: pointer;
}
#message {
margin: 20px;
text-align: center;
color: $white;
font-size: 30px;
font-weight: bold;
}
.choices {
margin-top: 30px;
text-align: center;
}
.choices button {
background-color: #2d3030;
display: inline-block;
width: 115px;
border: 4px solid $white;
border-radius: 50%;
font-size: 50px;
color: $white;
padding: 20px;
margin: 10px;
transition: all 0.4s ease;
}
.choices button:hover {
cursor: pointer;
color: #2d3030;
;
background-color: $white;
}
.challenge {
margin-top: 30px;
text-align: center;
color: $white;
font-size: 20px;
font-weight: bold;
}
.gray-glow {
border: 4px solid #787c77;
box-shadow: 0 0 15px 10px #787c77;
}
.green-glow {
border: 4px solid #31b43a;
box-shadow: 0 0 15px 10px #31b43a;
}
.red-glow {
border: 4px solid #d01115;
box-shadow: 0 0 15px 10px #d01115;
}
.choices-disabled {
display: none;
}
.newGame-disabled {
display: none;
}
.overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
&.show {
display: block;
}
}
.modal {
display: none;
background: $white;
width: 800px;
position: absolute;
top: 50%;
left: 50%;
transform: translate3d(-50%, -50%, 0);
padding: 20px;
text-align: center;
&.show {
display: block;
}
.close {
font-size: 20px;
position: absolute;
right: 0;
top: 0;
right: 5px;
padding: 5px;
color: $black;
text-decoration: none;
}
table {
text-align: center;
margin: 0 auto;
}
table th {
padding: 20px;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Rock Paper Scissors Final</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,900|Open+Sans:400,700,800&subset=latin-ext" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
<header>
<h1>Rock! Paper! Scissors!</h1>
</header>
<div id="trophy">
<i class="fas fa-trophy"></i>
<p id="numberOfWins"></p>
</div>
<div class="roundsCounter">
<p id="numberOfRounds"></p>
</div>
<div class="score-board">
<div id="user-label" class="badge">user</div>
<div id="computer-label" class="badge">comp</div>
<span id="user-score">0</span>:<span id="computer-score">0</span>
</div>
<div class="result">
<p>Rock beats Scissors
<br>Paper covers Rock
<br>Scissors cuts Paper</p>
</div>
<div class="newGame">
<p>New Game</p>
</div>
<p id="message"></p>
<div class="choices">
<button class="player-move" id="Rock" data-move="Rock">
<i class="fas fa-hand-rock"></i>
</button>
<button class="player-move" id="Paper" data-move="Paper">
<i class="fas fa-hand-paper"></i>
</button>
<button class="player-move" id="Scissors" data-move="Scissors">
<i class="fas fa-hand-scissors"></i>
</button>
</div>
<p class="challenge">Let me defeat you!</p>
<div class="overlay" id="modal-overlay">
<div class="modal" id="modal-one">
<i class="fas fa-times"></i>
<h2 id="endMessage">""</h2>
<h3><br>How it was?</h3>
<table>
<thead>
<tr>
<th>No.</th>
<th>Player move</th>
<th>Computer move</th>
<th>Game result</th>
</tr>
</thead>
<tbody id="resultsTableBody"></tbody>
</table>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
Related
I have tried to insert the data into the ToDo List and it is working but i am unable to edit the name and number field in the edit box of ToDo list.
And also the list is showing is not properly having padding and i tried to put padding in the list but whole list is shifting towards the left.
Also I tried with table concept in JavaScript but for that i need the loop and the database but i dont want to use the database or any other storage
var taskInput = document.getElementById("new-task");
var nameInput = document.getElementById("new-name");
var numberInput = document.getElementById("new-number");
var addButton = document.getElementsByTagName("button")[0];
var incompleteTask = document.getElementById("incomplete-tasks");
var completedTask = document.getElementById("completed-tasks");
var createNewTaskElement = function (taskString, nameString, numberString) {
var listItem = document.createElement("li");
var checkBox = document.createElement("input");
var label = document.createElement("label");
var label1 = document.createElement("label1");
var label2 = document.createElement("label2");
var editInput = document.createElement("input");
var editInput1 = document.createElement("input");
var editInput2 = document.createElement("input");
var editButton = document.createElement("button");
var deleteButton = document.createElement("button");
label.innerText = taskString;
label1.innerText = nameString;
label2.innerText = numberString;
checkBox.type = "checkbox";
editInput.type = "text";
editInput1.type = "text";
editInput2.type = "text";
editButton.innerText = "Edit";
editButton.className = "edit";
deleteButton.innerText = "Delete";
deleteButton.className = "delete";
listItem.appendChild(checkBox);
listItem.appendChild(label);
listItem.appendChild(editInput);
listItem.appendChild(label1);
listItem.appendChild(editInput1);
listItem.appendChild(label2);
listItem.appendChild(editInput2);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
alert("You added '" + label.innerText + "' to the ToDO list");
return listItem;
}
var addTask = function () {
var listItem = createNewTaskElement(taskInput.value,nameInput.value,numberInput.value);
if (taskInput.value == "") {
alert("You must enter a task");
}
else if (nameInput.value == "") {
alert("You must enter a Name");
}
else if (numberInput.value == "") {
alert("You must enter a Phone Number");
} else {
incompleteTask.appendChild(listItem);
}
bindTaskEvents(listItem, taskCompleted);
taskInput.value = "";
nameInput.value = "";
numberInput.value = "";
}
var editTask = function () {
var listItem = this.parentNode;
var editInput = listItem.querySelector('input[type=text]');
var label = listItem.querySelector("label");
var containsClass = listItem.classList.contains("editMode");
if (containsClass) {
label.innerText = editInput.value;
alert("You edited " + label.innerText);
} else {
editInput.value = label.innerText;
}
listItem.classList.toggle("editMode");
}
var deleteTask = function () {
var listItem = this.parentNode;
var ul = listItem.parentNode;
alert("You deleted " + listItem.querySelector("label").innerText);
ul.removeChild(listItem);
}
var taskCompleted = function () {
var listItem = this.parentNode;
completedTask.appendChild(listItem);
bindTaskEvents(listItem, taskIncomplete);
alert("You completed " + listItem.querySelector("label").innerText);
}
var taskIncomplete = function () {
var listItem = this.parentNode;
incompleteTask.appendChild(listItem);
bindTaskEvents(listItem, taskCompleted);
}
var bindTaskEvents = function (taskListItem, checkBoxEventHandler) {
var checkBox = taskListItem.querySelector("input[type=checkbox]");
var editButton = taskListItem.querySelector("button.edit");
var deleteButton = taskListItem.querySelector("button.delete");
editButton.onclick = editTask;
deleteButton.onclick = deleteTask;
checkBox.onchange = checkBoxEventHandler;
}
for (var i = 0; i < incompleteTask.children.length; i++) {
bindTaskEvents(incompleteTask.children[i], taskCompleted);
}
for (var i = 0; i < completedTask.children.length; i++) {
bindTaskEvents(completedTask.children[i], taskIncomplete);
}
var input = document.getElementById("new-number");
input.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
addTask();
}
});
.container {
height: 525px;
width: 450px;
margin: 100px auto;
}
ul {
margin: 0;
padding: 0;
}
li * {
float: left;
}
li,
h3 {
clear: both;
list-style: none;
font-family: Arial, Helvetica, sans-serif;
}
input,button {
outline: none;
}
button {
background: none;
border: 0px;
color: #888;
font-size: 15px;
width: 60px;
margin: 10px 0 0;
font-family: Lato, sans-serif;
cursor: pointer;
}
button:hover {
color: #333;
}
h3, label[for='new-task'] {
color: #333;
font-weight: 700;
font-size: 15px;
border-bottom: 2px solid #333;
padding: 30px 0 10px;
margin: 0;
text-transform: uppercase;
}
input[type="text"] {
margin: 0;
font-size: 18px;
line-height: 18px;
height: 18px;
padding: 10px;
border: 1px solid #ddd;
background: #fff;
border-radius: 8px;
font-family: Lato, sans-serif;
color: #888;
margin-left: 50px;
}
input[type="text"]:focus {
color: #333;
}
label[for='new-task'] {
display: block;
margin: 0 0 20px;
}
input#new-task,#new-name,#new-number {
width: 260px;
margin-bottom: 10px;
}
input:focus{
outline: none;
box-shadow: 0px 0px 5px #61C5FA;
border-color: #5AB0DB;
}
input:hover {
border: 1px solid #999;
border-radius: 5px;
}
p>button:hover {
color: #0FC57C;
}
li {
overflow: hidden;
padding: 20px 0;
border-bottom: 1px solid #eee;
}
li>input[type="checkbox"] {
margin: 0 10px;
position: relative;
top: 15px;
}
li>label {
font-size: 18px;
line-height: 40px;
width: 190px;
padding: 0 0 0 11px;
}
li>input[type="text"] {
width: 180px;
}
#completed-tasks label {
text-decoration: line-through;
color: #888;
}
ul li input[type=text] {
display: none;
}
ul li.editMode input[type=text] {
display: block;
}
ul li.editMode label {
display: none;
}
th{
padding-right: 70px;
}
<!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="style.css" type="text/css">
<title>To DO List</title>
</head>
<body style="background-color: #ebeff0">
<div class="container">
<h3 style="text-align: center;">Add Task</h3>
<br>
<label>Add Task</label>
<input id="new-task" type="text" required><br>
<label>Name</label>
<input id="new-name" type="text" required><br>
<label>Phone Number</label>
<input id="new-number" type="text" required><br>
<h3 style="text-align: center;">Todo</h3>
<ul id="incomplete-tasks">
</ul>
<h3 style="text-align: center;">Completed Tasks</h3>
<ul id="completed-tasks">
</ul>
</div>
</body>
<script type="text/javascript" src="main.js"></script>
</html>
I have created the class and then edited the inputs
var taskInput = document.getElementById("new-task");
var nameInput = document.getElementById("new-name");
var numberInput = document.getElementById("new-number");
var addButton = document.getElementsByTagName("button")[0];
var incompleteTask = document.getElementById("incomplete-tasks");
var completedTask = document.getElementById("completed-tasks");
var createNewTaskElement = function (taskString, nameString, numberString) {
var listItem = document.createElement("li");
var checkBox = document.createElement("input");
var label = document.createElement("label");
var label1 = document.createElement("label");
var label2 = document.createElement("label");
var editInput = document.createElement("input");
var editInput1 = document.createElement("input");
var editInput2 = document.createElement("input");
var editButton = document.createElement("button");
var deleteButton = document.createElement("button");
label.innerText = taskString;
label1.innerText = nameString;
label2.innerText = numberString;
label.className = "task";
label1.className = "name";
label2.className = "number";
checkBox.type = "checkbox";
editInput.type = "text";
editInput1.type = "text";
editInput2.type = "text";
editInput.className = "edit";
editInput1.className = "edit1";
editInput2.className = "edit2";
editButton.innerText = "Edit";
editButton.className = "edit";
deleteButton.innerText = "Delete";
deleteButton.className = "delete";
listItem.appendChild(checkBox);
listItem.appendChild(label);
listItem.appendChild(editInput);
listItem.appendChild(label1);
listItem.appendChild(editInput1);
listItem.appendChild(label2);
listItem.appendChild(editInput2);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
alert("You added '" + label.innerText + "' to the ToDO list");
return listItem;
}
var addTask = function () {
var listItem = createNewTaskElement(taskInput.value, nameInput.value, numberInput.value);
if (taskInput.value == "") {
alert("You must enter a task");
} else if (nameInput.value == "") {
alert("You must enter a Name");
} else if (numberInput.value == "") {
alert("You must enter a Phone Number");
} else {
incompleteTask.appendChild(listItem);
}
bindTaskEvents(listItem, taskCompleted);
taskInput.value = "";
nameInput.value = "";
numberInput.value = "";
}
var editTask = function () {
var listItem = this.parentNode;
var editInput = listItem.querySelector('.edit');
var editInput1 = listItem.querySelector('.edit1');
var editInput2 = listItem.querySelector('.edit2');
var label = listItem.querySelector(".task");
var label1 = listItem.querySelector(".name");
var label2 = listItem.querySelector(".number");
var containsClass = listItem.classList.contains("editMode");
if (containsClass) {
label.innerText = editInput.value;
label1.innerText = editInput1.value;
label2.innerText = editInput2.value;
alert("You edited " + label.innerText);
} else {
editInput.value = label.innerText;
editInput1.value = label1.innerText;
editInput2.value = label2.innerText;
}
listItem.classList.toggle("editMode");
}
var deleteTask = function () {
if (confirm("Are you sure you want to delete this task?") == true) {
var listItem = this.parentNode;
var ul = listItem.parentNode;
alert("You deleted " + listItem.querySelector("label").innerText);
} else {
alert("You cancelled the task");
}
ul.removeChild(listItem);
}
var taskCompleted = function () {
var listItem = this.parentNode;
if (confirm("Are you sure you want to mark this task as complete?") == true) {
completedTask.appendChild(listItem);
bindTaskEvents(listItem, taskIncomplete);
alert("You completed " + listItem.querySelector("label").innerText);
} else {
alert("You cancelled the task");
}
}
var taskIncomplete = function () {
var listItem = this.parentNode;
incompleteTask.appendChild(listItem);
bindTaskEvents(listItem, taskCompleted);
}
var bindTaskEvents = function (taskListItem, checkBoxEventHandler) {
var checkBox = taskListItem.querySelector("input[type=checkbox]");
var editButton = taskListItem.querySelector("button.edit");
var deleteButton = taskListItem.querySelector("button.delete");
editButton.onclick = editTask;
deleteButton.onclick = deleteTask;
checkBox.onchange = checkBoxEventHandler;
}
for (var i = 0; i < incompleteTask.children.length; i++) {
bindTaskEvents(incompleteTask.children[i], taskCompleted);
}
for (var i = 0; i < completedTask.children.length; i++) {
bindTaskEvents(completedTask.children[i], taskIncomplete);
}
var input = document.getElementById("new-number");
.container {
height: 525px;
width: 700px;
margin: 100px auto;
}
ul {
margin: 0;
padding: 0;
}
li * {
float: left;
}
li,
h3 {
clear: both;
list-style: none;
font-family: Arial, Helvetica, sans-serif;
}
input,button {
outline: none;
}
button {
background: none;
border: 0px;
color: #888;
font-size: 15px;
width: 60px;
margin: 10px 0 0;
font-family: Lato, sans-serif;
cursor: pointer;
}
button:hover {
color: #333;
}
h3, label[for='new-task'] {
color: #333;
font-weight: 700;
font-size: 15px;
border-bottom: 2px solid #333;
padding: 30px 0 10px;
margin: 0;
text-transform: uppercase;
}
input[type="text"] {
margin: 0;
font-size: 18px;
line-height: 18px;
height: 18px;
padding: 10px;
border: 1px solid #ddd;
background: #fff;
border-radius: 8px;
font-family: Lato, sans-serif;
color: #888;
margin-left: 50px;
}
input[type="text"]:focus {
color: #333;
}
label[for='new-task'] {
display: block;
margin: 0 0 20px;
}
input#new-task,#new-name,#new-number {
width: 260px;
margin-bottom: 10px;
}
input:focus{
outline: none;
box-shadow: 0px 0px 5px #61C5FA;
border-color: #5AB0DB;
}
input:hover {
border: 1px solid #999;
border-radius: 5px;
}
p>button:hover {
color: #0FC57C;
}
li {
overflow: hidden;
padding: 20px 0;
border-bottom: 1px solid #eee;
}
li>input[type="checkbox"] {
margin: 0 10px;
position: relative;
top: 15px;
}
li>label {
font-size: 18px;
line-height: 40px;
width: 100px;
padding: 0 0 0 11px;
}
li>input[type="text"] {
width: 100px;
}
li>button{
padding-left: 3px;
}
li>button:hover{
border: 1px solid black;
color: #c54f0f;
}
#completed-tasks label {
text-decoration: line-through;
color: #888;
}
ul li input[type=text] {
display: none;
}
ul li.editMode input[type=text] {
display: block;
}
ul li.editMode label {
display: none;
}
#AddBtn{
align-items: center;
border: 1px solid black !important;
background-color: white;
}
<!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="style.css" type="text/css">
<title>To DO List</title>
</head>
<body style="background-color: #ebeff0">
<div class="container">
<h3 style="text-align: center;">Add Task</h3>
<br>
<label>Add Task</label>
<input id="new-task" type="text" required><br>
<label style="padding-right: 05px;">Name</label>
<input id="new-name" type="text" required><br>
<label>Phone Number</label>
<input id="new-number" type="text" required><br>
<button id="AddBtn" onclick="addTask()">Add</button>
<h3 style="text-align: center;">Todo</h3>
<ul id="incomplete-tasks">
</ul>
<h3 style="text-align: center;">Completed Tasks</h3>
<ul id="completed-tasks">
</ul>
</div>
</body>
<script type="text/javascript" src="main.js"></script>
</html>
I'm trying to make a JavaScript quiz and I need the user to be able to go to the previous question to see or change his/her answer . The next button works with me but I have a problem with the previous button . what I also need is when the user goes back, the original answer should be saved. here is my code. I also put it on codepen
const questionNumber = document.querySelector(".question_number");
const questionText = document.querySelector(".question_text");
const optionContainer = document.querySelector(".option_container");
const answerIndecatorContainer = document.querySelector(".answer_indicator");
const homeBox = document.querySelector(".home_box");
const quizBox = document.querySelector(".quiz_box");
const resultBox = document.querySelector(".result_box");
const registerBox = document.querySelector(".register_box");
const timeBox = document.querySelector("time_box");
let questionCounter = 0;
let currentQuestion;
let availableQuestions = [];
let availableOptions = [];
let correctAnswers = 0;
let attempt = 0;
//push the question into availableQuestions array
function setAvailableQuestions(){
const totalQuestion = quiz.length;
for (let i=0; i<totalQuestion; i++){
availableQuestions.push(quiz[i])
}
}
// set question number and question options
function getNewQuestions(){
//set question number
questionNumber.innerHTML = "Question " + (questionCounter +1) + " of " + quiz.length;
// set question text
//get random questions
const questionIndex = availableQuestions[Math.floor(Math.random() * availableQuestions.length)]
currentQuestion = questionIndex;
questionText.innerHTML = currentQuestion.q;
//get the position of 'questionIndex' from the availableQuestions array
const index1 = availableQuestions.indexOf(questionIndex);
// remove the questionIndex from the availableQuestions array, so that the question does not repeat
availableQuestions.splice(index1,1);
//console.log(questionIndex)
//console.log(availableQuestions)
//set options
//get the length of options
const optionLen = currentQuestion.options.length
//push options into availableOptions array
for (let i=0; i<optionLen; i++){
availableOptions.push(i)
}
optionContainer.innerHTML = '';
let animationDelay = 0.15;
//create options in html
for(let i=0; i<optionLen; i++){
//random options
const optionIndex = availableOptions[Math.floor(Math.random() * availableOptions.length)];
//get the position of optionIndex from the availableOptions
const index2 = availableOptions.indexOf(optionIndex);
//remove the optionIndex from availableOptions
availableOptions.splice(index2,1);
const option = document.createElement("div");
option.innerHTML = currentQuestion.options[optionIndex];
option.id = optionIndex;
option.style.animationDelay= animationDelay + 's';
animationDelay = animationDelay + 0.15;
option.className = "option";
optionContainer.appendChild(option)
option.setAttribute("onclick", "getResult(this)");
}
questionCounter++
}
//get result of current attempt
function getResult(element){
const id = parseInt(element.id);
//get the answer by compairing the id of the options
if (id === currentQuestion.answer){
//set the green color to the correct option
element.classList.add("correct");
//add color to indector if answer is correct
updateAnswerIndecator("correct");
correctAnswers++;
}else{
//set the red color to the incorrect option
element.classList.add("wrong");
//add color to indector if answer is wrong
updateAnswerIndecator("wrong");
}
attempt++;
//unclickableOptions();
}
/*make all options unclickable once the user select
function unclickableOptions(){
const optionLen = optionContainer.children.length;
for(let i=0 ; i<optionLen ; i++){
optionContainer.children[i].classList.add("aready-answered");
}
}*/
function answerIndecator(){
answerIndecatorContainer.innerHTML = '';
const totalQuestion = quiz.length;
for (let i=0 ; i<totalQuestion ; i++){
const indecator = document.createElement("div");
answerIndecatorContainer.appendChild(indecator);
}
} function updateAnswerIndecator(markType){
answerIndecatorContainer.children[questionCounter-1].classList.add(markType);
}
function next(){
if (questionCounter === quiz.length){
quizOver();
}else{
getNewQuestions();
}
//
}
//Previous button
/*function previous(){
if (questionCounter == 0) {
questionCounter = quiz.length - 1;
} // reset question
else {
questionCounter--;
}
}*/
//
function quizOver(){
//when the quiz is over, the timer stops
//window.clearInterval(update);
clearInterval(countdownTimer);
upgradeTime = "-";
//show the registrer box
registerBox.classList.remove("hide");
//hide quiz box
quizBox.classList.add("hide");
}
function register(){
//show the result box
resultBox.classList.remove("hide");
//
registerBox.classList.add("hide");
quizResult();
}
//get the quiz result
function quizResult(){
resultBox.querySelector(".total_question").innerHTML = quiz.length;
resultBox.querySelector(".total_attempt").innerHTML = attempt;
resultBox.querySelector(".total_correct").innerHTML = correctAnswers;
resultBox.querySelector(".total_wrong").innerHTML = attempt - correctAnswers;
const persentage = (correctAnswers/quiz.length)*100;
resultBox.querySelector(".persentage").innerHTML = persentage.toFixed(2) + "%";
resultBox.querySelector(".total_score").innerHTML = correctAnswers + " / " + quiz.length;
}
function resetQuiz(){
questionCounter = 0;
correctAnswers = 0;
attempt = 0;
}
function tryAgainQuiz(){
//hide the resultBox
resultBox.classList.add("hide");
//show the quizBox
quizBox.classList.remove("hide");
resetQuiz();
startQuiz();
}
function goToHome(){
//hide the result box
resultBox.classList.add("hide");
//show home box
homeBox.classList.remove("hide");
resetQuiz();
}
//###STARTING POINT###
function startQuiz() {
//start timer
upgradeTime = 20;
seconds = upgradeTime;
//hide home Box
homeBox.classList.add("hide");
//show the quiz box
quizBox.classList.remove("hide");
//first we set all questions in availableQuestions array
setAvailableQuestions();
//second we will call the getNewQuestions() funcrion
getNewQuestions();
//to create indecator of answers
answerIndecator();
}
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = "الوقت المتبقي :" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "انتهى الوقت";
quizBox.classList.add("hide");
registerBox.classList.remove("hide");
//show the result box
/*resultBox.classList.remove("hide");
quizResult();*/
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
window.onload = function (){
homeBox.querySelector(".total_question").innerHTML = quiz.length;
}
//array of objects
const quiz = [
{
q:' أوجد قيمة: \(\left( {3 + \sqrt 3 } \right) - \sqrt 3 + 18\) ',
options:['٨٤','\(81 + \sqrt 6 \)','٧٨','٧٩'],
answer:0
},
{
q:' HOW',
options:['٣٤,١ دقيقة ','٣,١٤ دقيقة ','٣١٤ دقيقة','٣٤١ دقيقة '],
answer:0
},
{
q:'ا قيمة \(\frac{{{9^4} - {9^6}}}{{{9^2} - {9^3}}}\) ',
options:['800','810','9','\({9^3}\)'],
answer:0
},
{
q:'ذا كانت مساحة الدائرة الصغيرة = 16 ط فإن محيط المنطقة المظللة = ',
options:['64 ط','4ط','8ط','24'],
answer:3
},
{
q:'حتاج ارض زراعية 15 يوم لينمو فيها \(1.2 + {10^8}\) من لا شيء فكم تحتاج لينمو فيها \(4.0 + {10^8}\) من لا شيء',
options:['18','60','13','45'],
answer:1
},
{
q:'حتاج ارض زراعية 15 يوم لينمو فيها \(1.2 + {10^8}\) من لا شيء فكم تحتاج لينمو فيها \(4.0 + {10^8}\) من لا شيء',
options:['18','60','13','45'],
answer:1
}
]
#import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght#0,400;0,500;0,600;0,700;1,700&display=swap');
body{
margin: 0;
font-size: 16px;
background-color: #009688;
font-family: 'Montserrat', sans-serif;
font-weight: 400;
}
*{
box-sizing: border-box;
margin:0;
padding:0;
outline:none;
}
.custom_box{
max-width: 700px;
background-color: #ffffff;
margin: 49px auto;
padding: 30px;
border-radius: 10PX;
animation: fadeInRight 1s ease;
}
#keyframes fadeInRight{
0%{
transform: translateX(40px);
opacity: 0;
}
100%{
transform: translateX(0px);
opacity: 1;
}
}
.custom_box::before,
.custom_box::after{
content: '';
clear: both;
display: table;
}
.custom_box.hide{
display: none;
}
.home_box h3{
font-size: 18px;
color:#000000;
font-weight:500;
margin-bottom: 15px;
line-height: 25px;
}
.home_box p{
font-size: 16px;
margin-bottom: 10px;
line-height:22px;
color:#000000;
font-weight:400;
}
.home_box p span{
font-weight: 500;
}
.home_box .btn{
margin-top: 20px;
}
.btn{
padding: 15px 45px;
background-color: #009688;
color: #ffffff;
border:none;
border-radius:5px;
font-family: 'Montserrat', sans-serif;
font-size:16px;
cursor:pointer;
display: inline-block;
}
.quiz_box .question_number,
.quiz_box .question_text,
.quiz_box .option_container,
.quiz_box .next_question_btn,
.quiz_box .answer_indicator{
width: 100%;
float: left;
}
.quiz_box .question_number{
font-size: 18px;
color:#009688;
font-weight: 600;
border-bottom: 1px solid #cccccc;
padding-bottom: 10px;
line-height: 25px;
}
.quiz_box .question_text{
font-size: 22px;
color:#000000;
line-height: 28px;
font-weight: 400;
padding: 20px 0;
margin: 0;
}
.quiz_box .option_container .option{
background-color: #cccccc;
padding:13px 15px;
font-size: 16px;
line-height: 22px;
color: #000000;
border-radius: 5px;
margin-bottom: 10px;
cursor: pointer;
text-transform: capitalize;
opacity: 0;
animation: fadeIn 0.3s ease forwards;
position: relative;
overflow: hidden;
}
.quiz_box .option_container .option.aready-answered{
pointer-events: none;
}
#keyframes fadeIn{
0%{
opacity: 0;
}
100%{
opacity: 1;
}
}
.quiz_box .option_container .option.correct::before{
content: '';
position: absolute;
left:0;
top: 0;
height: 100%;
width: 100%;
background-color: green;
z-index: -1;
animation: slideInLift .5s ease forwards
}
#keyframes slideInLift{
0%{
transform: translateX(-100%);
}
100%{
transform: translateX(0%);
}
}
.quiz_box .option_container .option.correct{
color: #ffffff;
}
.quiz_box .btn{
margin: 15px 0;
}
.quiz_box .answer_indicator{
border-top: 1px solid #cccccc;
}
.quiz_box .answer_indicator div{
height: 40px;
width: 40px;
display: inline-block;
background-color: #cccccc;
border-radius: 50%;
margin-right:3px;
margin-top: 15px;
}
.quiz_box .answer_indicator div.correct{
background-color: green;
}
.quiz_box .answer_indicator div.wrong{
background-color: red;
}
.result_box{
text-align: center;
}
.result_box.hide{
display: none;
}
.result_box h1{
font-size: 36px;
line-height: 42px;
color: #009688;
}
.result_box table{
width: 100%;
border-collapse: collapse;
margin:30px 0;
}
.result_box table td{
border:1px solid #cccccc;
padding: 8px 15px;
font-weight: 500;
color: #000000;
width: 50%;
text-align: left;
font-size: 18px;
}
.result_box .btn{
margin-right: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" type="text/css" href="random_style.css">
</head>
<body>
<div class="home_box custom_box">
<h3>هذا الاختبار يحتوي على ٢٥ سؤال بمدة ٢٥ دقيقة</h3>
<p>عدد الأسئلة: <span class="total_question"></span></p>
<button type="button" class="btn" onclick="startQuiz()">ابدأ الاختبار </button>
</div>
<div class="time_box custom_box ">
<span id="countdown" class="timer"></span>
<!-- <text>الوقت المتبقي: <text id="time001">1200</text></text><br/>-->
</div>
<div class="quiz_box custom_box hide">
<div class="question_number">
</div>
<div class="question_text">
</div>
<div class="option_container">
</div>
<div class="next_question_btn">
<button type="button" class="btn" onclick="next()">التالي</button>
<!-- <button type="button" class="btn" onclick="previous()">السابق</button>-->
</div>
<div class="answer_indicator">
</div>
</div>
<div class="register_box custom_box hide" style="direction: rtl;">
<form >
<p>الرجاء ادخال بياناتك للحصول على نتيجة اختبارك </p><br>
<label for="uname">اسمك الكامل <br></label>
<input type="text" class="w3-input w3-border w3-round-large" placeholder="ادخل اسمك الكامل " name="uname" required><br>
<label for="email">الايميل <br></label>
<input type="email" class="w3-input w3-border w3-round-large" placeholder="ادخل اسمك الكامل " name="email" required><br>
<label for="phone">رقم الجوال (اختياري )<br></label>
<input type="number" class="w3-input w3-border w3-round-large" placeholder="ادخل رقم الجوال " name="phone"><br>
<button type="button" value="submit" onclick="register()"class="btn">تسجيل </button>
</form >
</div>
<div class="result_box custom_box hide">
<h1>النتيجة</h1>
<table>
<tr>
<td> total questions</td>
<td><span class="total_question"></span></td>
</tr>
<tr>
<td>attempt</td>
<td><span class="total_attempt"></span></td>
</tr>
<tr>
<td>correct</td>
<td><span class="total_correct"></span></td>
</tr>
<tr>
<td>wrong</td>
<td><span class="total_wrong"></span></td>
</tr>
<tr>
<td>persentage</td>
<td><span class="persentage"></span></td>
</tr>
<tr>
<td>your total score</td>
<td><span class="total_score"></span></td>
</tr>
</table>
<button type="button" class="btn" onclick="tryAgainQuiz()">try again</button>
<button type="button" class="btn" onclick="goToHome()">go to home</button>
</div>
<script src="quistion.js" charset="utf-8" type="text/javascript"></script>
<script src="app.js"></script>
</body>
</html>
I am teaching myself JavaScript and to improve my programming logic I decided to make a Hangman game. Everything works but I am having a problem with the win or lose function. The logic is If the indexCompare array length is === to correctGuesses Array length. Display You win If your lives are === to 0 Display you lose. But for some reason when a correct guess is pushed to the correctGuesses Array if it is a letter that appears more then once in the word. Only 1 occurrence of that letter is added to the array. So certain words never result in a win. And the win condition is never fulfilled. And I think it has something to do with me getting the value from the event Object. I might be wrong though. Any help would be greatly appreciated.
var gameCore = window.onload = function() {
var hangmanWords = ["super", "venus", "spanish", "darkness", "tenebris", "meatball", "human", "omega", "alpha", "isochronism", "supercalifragilisticexpialidocious"];
var commentsArray = ["I belive in you! You can do the thing!", "There is still hope keep trying", "Third times a charm", "You can do this", "Think player think! The counter is almost out", "Never give up", "The last melon 0.0", "What the frog you had one job u_u"];
var hints = ["The opposite of ordinary.", "A planet in are solar system.", "One of the largest languages in the world", "The opposite of light", "A rare word for darkness", "A tasty kind of sphear AKA 'ball' ", "You are A?", "A letter in the greek alphabet.", "Another letter in the greek alphabet.", "A word about time that almost no one uses.", "A big word that you know if you have seen mary poppins but never use."]
var correctGuesses = [];
var lives = 7;
var indexCompare = [];
var choosenWord = []
var arrayCounter = [];
//get elements
var showHint = document.getElementById("hint");
var showLivesLeft = document.getElementById("lives");
var showComments = document.getElementById("comment");
var showLoseOrWin = document.getElementById("winOrLoseDisplay");
// click assigner function
var clickAssigner = function(event) {
var letterHandler = document.getElementsByClassName("letters");
for (var i = 0; i < letterHandler.length; i++) {
letterHandler[i].addEventListener("click", compare, false);
}
var hintHandler = document.getElementById("hint");
hintHandler.addEventListener("click", hint, false);
}
clickAssigner(event);
function hint(event) {
if (arrayCounter[0] === 0) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 1) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 2) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 3) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 4) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 5) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 6) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 7) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 8) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 9) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 10) {
showHint.innerHTML = hints[arrayCounter]
};
}
// word selector and display function
// arrayCounter is the same as i
function wordSelector() {
var randomNumber = Math.floor(Math.random() * (10 - 0 + 1)) + 0;
arrayCounter.push(randomNumber);
var livesContainer = document.createElement("p");
var livesNumber = lives;
showLivesLeft.setAttribute("id", "livesNumbers");
showLivesLeft.appendChild(livesContainer);
livesContainer.innerHTML = livesNumber;
var selectedWord = hangmanWords[arrayCounter];
var wordDisplay = document.getElementById("wordDisplay");
var correctWordDisplay = document.createElement("ul");
var playerGuess;
for (var i = 0; i < selectedWord.length; i++) {
correctWordDisplay.setAttribute("id", "correctWordDisplay-UL");
playerGuess = document.createElement("li");
playerGuess.setAttribute("class", "playerGuess");
playerGuess.innerHTML = "_";
indexCompare.push(playerGuess);
wordDisplay.appendChild(correctWordDisplay);
correctWordDisplay.appendChild(playerGuess);
}
}
wordSelector();
// compare function // decrement lives function // remove health bar
function compare(event) {
var livesDisplay = document.getElementById("livesNumbers");
var btnVal = event.target.value;
var word = hangmanWords[arrayCounter];
for (var i = 0; i < word.length; i++) {
if (word[i] === btnVal) {
indexCompare[i].innerHTML = btnVal;
}
}
var c = word.indexOf(btnVal);
if (c === -1) {
event.target.removeAttribute("letters");
event.target.setAttribute("class", "incorrectLetter");
event.target.removeEventListener("click", compare);
lives -= 1;
livesDisplay.innerHTML = lives;
} else {
event.target.removeAttribute("letters");
event.target.setAttribute("class", "correctLetter");
event.target.removeEventListener("click", compare);
correctGuesses.push(event.target.value);
}
comments();
winOrLose();
// console.log(event);
// console.log(word);
}
// comment function
function comments() {
if (lives === 7) {
showComments.innerHTML = "<p>" + commentsArray[0] + "</p>"
};
if (lives === 6) {
showComments.innerHTML = "<p>" + commentsArray[1] + "</p>"
};
if (lives === 5) {
showComments.innerHTML = "<p>" + commentsArray[2] + "</p>"
};
if (lives === 4) {
showComments.innerHTML = "<p>" + commentsArray[3] + "</p>"
};
if (lives === 3) {
showComments.innerHTML = "<p>" + commentsArray[4] + "</p>"
};
if (lives === 2) {
showComments.innerHTML = "<p>" + commentsArray[5] + "</p>"
};
if (lives === 1) {
showComments.innerHTML = "<p>" + commentsArray[6] + "</p>"
};
if (lives === 0) {
showComments.innerHTML = "<p>" + commentsArray[7] + "</p>"
};
}
// win or lose function
function winOrLose() {
for (var i = 0; i < indexCompare.length; i++) {
if (indexCompare.length === correctGuesses.length) {
showLoseOrWin.innerHTML = "<p>" + "YOU WIN!!! :D" + "</p>";
}
}
if (lives === 0) {
showLoseOrWin.innerHTML = "<p>" + "YOU LOSE u_u" + "</p>";
}
}
function reset() {
}
}
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html,body,div,span,applet,object,iframe,h1,h2,
h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,
img,ins,kbd,q,
s,samp,small,strike,strong,sub,sup,tt,var,b,u,
i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,
legend,table,caption,tbody,tfoot,thead,tr,th,
td,article,aside,canvas,details,embed,figure,figcaption,
footer,header,hgroup,menu,nav,output,ruby,section,
summary,time,mark,audio,video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section {
display: block;
}
body {
line-height: 1;
}
ol,ul {
list-style: none;
}
blockquote,
q {
quotes: none;
}
blockquote:before,
blockquote:after,
q:before,
q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
#container {
overflow: hidden;
max-width: 60%;
background-color: yellowgreen;
margin: 7em auto;
padding: 1em;
}
#wordDisplay {
height: 6em;
background-color: orangered;
margin-bottom: 0.2em;
text-align: center;
padding-top: 2.4em;
font-size: 26px;
display: flex;
justify-content: center;
}
#correctWordDisplay-UL {
list-style: none;
display: flex;
justify-content: center;
}
.playerGuess {
margin: 0em 0.08em;
font-size: 30px;
}
#hint {
max-width: 26em;
padding: 1em;
background-color: skyblue;
border: 0.5em ridge gold;
font-weight: 900;
margin: 0em auto 1em auto;
text-align: center;
}
#hint:hover {
background-color: coral;
cursor: pointer;
font-style: oblique;
}
#letterDiplay {
width: 14em;
float: left;
text-align: center;
background: crimson;
padding: 1em;
}
.letters {
margin: 0.3em auto;
text-align: center;
width: 4em;
height: 3em;
font-weight: 900;
background-color: darkorange;
border: 3px ridge darkblue;
}
.letters:hover {
background: steelblue;
color: white;
cursor: pointer;
}
#theChanceCounter {
text-align: center;
float: right;
width: 14em;
background-color: crimson;
height: 28.9em;
}
/* #lives{
width: 3em;
height: 3em;
margin: 1em auto 0em auto;
background-color: teal;
color: black;
font-weight: 900;
text-align: center;
} */
#livesNumbers {
margin-top: 1em;
border: 3px solid black;
width: 3em;
height: 3em;
padding: 0.9em 0em 0em 0em;
margin: 1em auto 0em auto;
background-color: teal;
color: black;
font-weight: 900;
text-align: center;
}
.correctLetter {
margin: 0.3em auto;
text-align: center;
width: 4em;
height: 3em;
font-weight: 900;
background: green;
color: yellow;
}
.incorrectLetter {
margin: 0.3em auto;
text-align: center;
width: 4em;
height: 3em;
font-weight: 900;
background: red;
color: yellow;
}
#comment {
background-color: forestgreen;
width: 12em;
height: 4em;
padding: 1em 0.4em 0em 0.4em;
margin: 0.3em auto 0.3em auto;
border: 3px solid black;
}
#winOrLoseDisplay {
width: 18em;
padding: 1em;
background-color: skyblue;
border: 0.5em ridge orange;
font-weight: 900;
margin: 0em auto 1em 1.4em;
text-align: center;
float: left;
}
<div id="container">
<section id="wordDisplay">
</section>
<section id="hint">Click for hint.</section>
<section id="letterDiplay">
<button class="letters" value="a">A</button>
<button class="letters" value="b">B</button>
<button class="letters" value="c">C</button>
<button class="letters" value="d">D</button>
<button class="letters" value="e">E</button>
<button class="letters" value="f">F</button>
<button class="letters" value="g">G</button>
<button class="letters" value="h">H</button>
<button class="letters" value="i">I</button>
<button class="letters" value="j">J</button>
<button class="letters" value="k">K</button>
<button class="letters" value="l">L</button>
<button class="letters" value="m">M</button>
<button class="letters" value="n">N</button>
<button class="letters" value="o">O</button>
<button class="letters" value="p">P</button>
<button class="letters" value="q">Q</button>
<button class="letters" value="r">R</button>
<button class="letters" value="s">S</button>
<button class="letters" value="t">T</button>
<button class="letters" value="u">U</button>
<button class="letters" value="v">V</button>
<button class="letters" value="w">W</button>
<button class="letters" value="x">X</button>
<button class="letters" value="y">Y</button>
<button class="letters" value="z">Z</button>
</section>
<section id="winOrLoseDisplay"></section>
<section id="theChanceCounter">
<div id="lives">
</div>
<div id="comment">
</div>
</section>
</div>
</script>
Can you help me find out why my code isn't working?
I have to chceck if password is
a)4-6 characters long (one or more numbers must be included) for password to be medium
b)7 and more characters (one or more numbers must be included) for strong. c)Anything else than a) and b) is weak.
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form>
<p>
<input type="password" id="password" />
<button onlick="spr()">check</button>
</p>
</form>
<div id="result"></div>
<script>
function spr()
{
var str = document.getElementById("password");
var medium = /^[A-Za-z0-9]{4,6}$/;
var strong = /^[A-Za-z0-9]{7,}$/;
if(medium.test(str))
document.getElementById("result").innerHTML="medium";
else if(silne.test(str))
document.getElementById("result").innerHTML="strong";
else
document.getElementById("result").innerHTML="weak";
return false;
}
</script>
</body>
</html>
follow this https://jsfiddle.net/umesh1990/hxjf74cz/35/#
i have done this using javascript
function password_validate(txt) {
var val1 = 0;
var val2 = 0;
var val3 = 0;
var val4 = 0;
var val5 = 0;
var counter, color, result;
var flag = false;
if (txt.value.length <= 0) {
counter = 0;
color = "transparent";
result = "";
}
if (txt.value.length < 8 & txt.value.length > 0) {
counter = 20;
color = "red";
result = "Short";
} else {
document.getElementById(txt.id + "error").innerHTML = " ";
txt.style.borderColor = "grey";
var regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/;
// document.getElementById("pass_veri").style.display="block";
var fletter = /[a-z]/;
if (fletter.test(txt.value)) {
val1 = 20;
} else {
val1 = 0;
}
//macth special character
var special_char = /[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/;
if (special_char.test(txt.value)) {
val2 = 30;
} else {
val = 0;
}
/*capital_letter*/
var cap_lett = /[A-Z]/;
if (cap_lett.test(txt.value)) {
val3 = 20;
} else {
val = 0;
}
/*one numeric*/
var num = /[0-9]/;
if (num.test(txt.value)) {
val4 = 20;
} else {
val4 = 0;
}
/* 8-15 character*/
var range = /^.{8,50}$/;
if (range.test(txt.value)) {
val5 = 10;
} else {
val5 = 0;
}
counter = val1 + val2 + val3 + val4 + val5;
if (counter >= 30) {
color = "skyblue";
result = "Fair";
}
if (counter >= 50) {
color = "gold";
result = "Good";
}
if (counter >= 80) {
color = "green";
result = "Strong";
}
if (counter >= 90) {
color = "green";
result = "Very Strong";
}
}
document.getElementById("prog").style.width = counter + "%";
document.getElementById("prog").style.backgroundColor = color;
document.getElementById("result").innerHTML = result;
document.getElementById("result").style.color = color;
}
body {
font-family: 'Rajdhani', sans-serif;
background-color: #E4E4E4;
}
/* tooltip*/
.hint {
width: 258px;
background: red;
position: relative;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
position: absolute;
left: 0px;
border: 1px solid #CC9933;
background-color: #FFFFCC;
display: none;
padding: 20px;
font-size: 11px;
}
.hint:before {
content: "";
position: absolute;
left: 100%;
top: 24px;
width: 0;
height: 0;
border-top: 17px solid transparent;
border-bottom: 1px solid transparent;
border-left: 22px solid #CC9933;
}
.hint:after {
content: "";
position: absolute;
left: 100%;
top: 26px;
width: 0;
height: 0;
border-top: 14px solid transparent;
border-bottom: 1px solid transparent;
border-left: 20px solid #FFFFCC;
}
.parent {
position: relative;
}
.progress {
height: 7px;
}
#progres {
display: block;
}
p {
margin: 0px;
font-weight: normal;
}
.form-control {
width: none;
margin-left: 260px;
margin-top: 25px;
width: 200px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group col-lg-12 parent ">
<label class="hint" id="pass-hint">
Password Strength:<span id="result"></span>
<br>
<div class="progress" id="progres">
<div class="progress-bar progress-bar-danger" role="progressbar" id="prog">
</div>
</div>
<p> passowrd must have atleast 8 charatcer</p>
</label>
<input type="password" class="form-control" data-toggle="tooltip" data-placement="left" id="pass" onfocus="document.getElementById('pass-hint').style.display='block'" onblur="document.getElementById('pass-hint').style.display='none'" placeholder="**********"
oninput="password_validate(this);document.getElementById('progres').style.display='block';">
<i class=" form-control-feedback" id="passsuccess" aria-hidden="true"></i>
<span id="passerror" class="help-block error"></span>
</div>
it may help you
I'm looking for a simple Password Strength Visualizer (like gmail's when you create a new account). I want to show the user how good their password is visually.
Does anyone have some source code they'd like to share? :)
i found this https://jsfiddle.net/umesh1990/hxjf74cz/35/# i have implement using javascript
function password_validate(txt) {
var val1 = 0;
var val2 = 0;
var val3 = 0;
var val4 = 0;
var val5 = 0;
var counter, color, result;
var flag = false;
if (txt.value.length <= 0) {
counter = 0;
color = "transparent";
result = "";
}
if (txt.value.length < 8 & txt.value.length > 0) {
counter = 20;
color = "red";
result = "Short";
} else {
document.getElementById(txt.id + "error").innerHTML = " ";
txt.style.borderColor = "grey";
var regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/;
// document.getElementById("pass_veri").style.display="block";
var fletter = /[a-z]/;
if (fletter.test(txt.value)) {
val1 = 20;
} else {
val1 = 0;
}
//macth special character
var special_char = /[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/;
if (special_char.test(txt.value)) {
val2 = 30;
} else {
val = 0;
}
/*capital_letter*/
var cap_lett = /[A-Z]/;
if (cap_lett.test(txt.value)) {
val3 = 20;
} else {
val = 0;
}
/*one numeric*/
var num = /[0-9]/;
if (num.test(txt.value)) {
val4 = 20;
} else {
val4 = 0;
}
/* 8-15 character*/
var range = /^.{8,50}$/;
if (range.test(txt.value)) {
val5 = 10;
} else {
val5 = 0;
}
counter = val1 + val2 + val3 + val4 + val5;
if (counter >= 30) {
color = "skyblue";
result = "Fair";
}
if (counter >= 50) {
color = "gold";
result = "Good";
}
if (counter >= 80) {
color = "green";
result = "Strong";
}
if (counter >= 90) {
color = "green";
result = "Very Strong";
}
}
document.getElementById("prog").style.width = counter + "%";
document.getElementById("prog").style.backgroundColor = color;
document.getElementById("result").innerHTML = result;
document.getElementById("result").style.color = color;
}
body {
font-family: 'Rajdhani', sans-serif;
background-color: #E4E4E4;
}
/* tooltip*/
.hint {
width: 258px;
background: red;
position: relative;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
position: absolute;
left: 0px;
border: 1px solid #CC9933;
background-color: #FFFFCC;
display: none;
padding: 20px;
font-size: 11px;
}
.hint:before {
content: "";
position: absolute;
left: 100%;
top: 24px;
width: 0;
height: 0;
border-top: 17px solid transparent;
border-bottom: 1px solid transparent;
border-left: 22px solid #CC9933;
}
.hint:after {
content: "";
position: absolute;
left: 100%;
top: 26px;
width: 0;
height: 0;
border-top: 14px solid transparent;
border-bottom: 1px solid transparent;
border-left: 20px solid #FFFFCC;
}
.parent {
position: relative;
}
.progress {
height: 7px;
}
#progres {
display: block;
}
p {
margin: 0px;
font-weight: normal;
}
.form-control {
width: none;
margin-left: 260px;
margin-top: 25px;
width: 200px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="form-group col-lg-12 parent ">
<label class="hint" id="pass-hint">
Password Strength:<span id="result"></span>
<br>
<div class="progress" id="progres">
<div class="progress-bar progress-bar-danger" role="progressbar" id="prog">
</div>
</div>
<p> passowrd must have atleast 8 charatcer</p>
</label>
<input type="password" class="form-control" data-toggle="tooltip" data-placement="left" id="pass" onfocus="document.getElementById('pass-hint').style.display='block'" onblur="document.getElementById('pass-hint').style.display='none'" placeholder="**********"
oninput="password_validate(this);document.getElementById('progres').style.display='block';">
<i class=" form-control-feedback" id="passsuccess" aria-hidden="true"></i>
<span id="passerror" class="help-block error"></span>
</div>
Choose the one you like most:
10 Password Strength Meter Scripts For A Better Registration Interface
Drupal has one built into Drupal 6. The code for the backport to Drupal 5 may be of use to you.
This one seems great: http://www.geekwisdom.com/dyn/passwdmeter.
Depending on the password score, you can show a green, yellow or red marker, or whatever you want.