I'm recently watching JavaScript online course, and I built the 'pig-game'.
There's input box for set the winning score.
I want to improve it if user types the value that is not 'number', then it's value will change automatically to '100' as default.
I put if statement there, but I can't solve It's parameter.
e.g. if(input === number) doesn't work.
You can check my github (https://github.com/wonkooklee/pig-game)
and code is below
//
document.querySelector('.btn-hold').addEventListener('click', function() {
if (gamePlaying) {
scores[activePlayer] += roundScore;
document.getElementById(`score-${activePlayer}`).textContent = scores[activePlayer];
let input = document.getElementById('scoreSet').value;
let winningScore;
if (input === number) { // This is that I'm dealing with
winningScore = input;
} else {
document.getElementById('scoreSet').value = '100';
}
if (scores[activePlayer] >= winningScore) {
document.getElementById(`name-${activePlayer}`).textContent = 'WINNER!';
document.querySelector(`.player-${activePlayer}-panel`).classList.add('winner');
document.querySelector(`.player-${activePlayer}-panel`).classList.remove('active');
diceDOM.style.display = 'none';
gamePlaying = false;
} else {
nextPlayer();
}
}
});
Here is what you want (if what you want is to check if an input has been enter by the user the value will not be "" (which would be falsy), so the test if(input) will be true):
document.querySelector('.btn-hold').addEventListener('click', function () {
if (gamePlaying) {
scores[activePlayer] += roundScore;
document.getElementById(`score-${activePlayer}`).textContent = scores[activePlayer];
let input = document.getElementById('scoreSet').value;
let winningScore;
if (input) {
winningScore = input;
} else {
document.getElementById('scoreSet').value = '100';
}
if (scores[activePlayer] >= winningScore) {
document.getElementById(`name-${activePlayer}`).textContent = 'WINNER!';
document.querySelector(`.player-${activePlayer}-panel`).classList.add('winner');
document.querySelector(`.player-${activePlayer}-panel`).classList.remove('active');
diceDOM.style.display = 'none';
gamePlaying = false;
} else {
nextPlayer();
}
}
});
I am trying to make a number guessing game where the user gets 3 chances to guess a number between 1 to 10 and after the third try if they don't manage to guess the number correctly, they'll lose and the number input becomes disabled.
So my variable "tryNum" is meant to be the number of guesses the user gets which I set to be 3. And I then wrote my if statement whereby every time the user guesses the number incorrectly, the value of tryNum decreases by 1. And based on my code, by the time the user guesses 3 incorrect numbers, the input should become disabled and an error message should be displayed. However, when I run my code, it takes 4 incorrect guesses instead of 3 for my code to execute.
I am not sure why this is. Any help would be greatly appreciated.
Here is my code:
let min = 1,
max = 10,
winningNum = 3;
tryNum = 3;
function btnClciked(){
guessedNum = parseInt(userInput.value);
if (tryNum > 0){
let status;
if (isNaN(guessedNum) || guessedNum < min || guessedNum > max ){
if(document.querySelector(".error-display")){
status = false;
} else {
status = true;
}
isNaN(guessedNum) ? createDivElement("You havn't entered any number!", status, "#eb992d","black", true) : createDivElement(`You must guess a number between ${min} and ${max}`, status, "#eb992d", "black", true);
}
else if (guessedNum === winningNum){
status = true;
userInput.disabled = true;
userInput.style.borderColor = "green";
submitBtn.value = "Play Again!";
submitBtn.className += "play-again";
createDivElement(`Congratulations! You guessed the winning number: ${winningNum} Correctly!`, status, "green", "white");
}
else {
status = true;
userInput.style.borderColor = "red";
userInput.value = "";
tryNum -= 1;
createDivElement(`${guessedNum} isn't the winning number! You have ${tryNum} more guesses left!`, status, "red", "white");
}
} else {
userInput.disabled = true;
status = true;
userInput.style.borderColor = "red";
submitBtn.value = "Play Again!";
submitBtn.className += "play-again";
createDivElement(`Game Over! The winning number was ${winningNum}.`, status, "red", "white");
}
}
When the user guesses it wrong, you should check if tryNum is equal to 0, in which case you should show that it is Game Over.
function btnClciked(){
guessedNum = parseInt(userInput.value);
if (tryNum > 0){
let status;
if (isNaN(guessedNum) || guessedNum < min || guessedNum > max ){
if(document.querySelector(".error-display")){
status = false;
} else {
status = true;
}
isNaN(guessedNum) ? createDivElement("You havn't entered any number!", status, "#eb992d","black", true) : createDivElement(`You must guess a number between ${min} and ${max}`, status, "#eb992d", "black", true);
}
else if (guessedNum === winningNum){
status = true;
userInput.disabled = true;
userInput.style.borderColor = "green";
submitBtn.value = "Play Again!";
submitBtn.className += "play-again";
createDivElement(`Congratulations! You guessed the winning number: ${winningNum} Correctly!`, status, "green", "white");
}
else {
status = true;
userInput.style.borderColor = "red";
userInput.value = "";
tryNum -= 1;
if(tryNum != 0){
createDivElement(`${guessedNum} isn't the winning number! You have ${tryNum} more guesses left!`, status, "red", "white");
} else {
userInput.disabled = true;
status = true;
userInput.style.borderColor = "red";
submitBtn.value = "Play Again!";
submitBtn.className += "play-again";
createDivElement(`Game Over! The winning number was ${winningNum}.`, status, "red", "white");
}
}
}
}
Basically when you don't guess the number the third time the value of tryNum is 0 but you have to make another guess in order to trigger the first if statement and enter in the final else block.
The simplest solution is to put the final else block into an if statement below tryNum-=1 to check if the variable is 0
var input = document.getElementById("wordTyped");
var word = document.getElementById("wordGenerated").innerHTML;
window.onload = function() {
window.onkeydown = submit;
function submit(evt) {
if (evt.key == "Enter" && input.value == word) {
input.value = "";
input.style.color = "black";
} else if (evt.key == "Enter" && input.value != word) {
for (i = 0; i < word.length; i++) {
// Below is what I'm querying about
if (input.value[i] != word[i]) {
input.style.color = "red";
}
}
}
}
}
<div id="wordGenerated">illustration</div>
<input id="wordTyped" type="text" />
I don't think what I'm asking is even possible but I want to try changing the color of the input character that does not match with the word
For example,
wordGenerated: illustration
wordTyped: iilustration
The second 'i' in wordTyped should then change its color to red on Enter
I tried doing input.value.style.color[i] = "red" and input.value[i].style.color = "red", but these in return give a TypeError color of undefined.
The code above changed the whole input text color into red.
You just have to wrap your letters in a span element.
NB: the code below is just a prof of concept, I didn't optimize it.
I left optimization part to you.
good luck.
var input = document.getElementById("wordTyped");
var word = document.getElementById("wordGenerated").innerHTML;
window.onload = function() {
window.onkeydown = submit;
function submit(evt) {
var newWord=document.getElementById("wordGenerated");
newWord.innerHTML="";
if (evt.key == "Enter" && input.value == word) {
input.value = "";
input.style.color = "black";
} else if (evt.key == "Enter" && input.value != word) {
for (i = 0; i < input.value.length; i++) {
// Below is what I'm querying about
if (input.value[i] != word[i]) {
var child = document.createElement( "span" );
child.className='colored';
child.innerHTML = input.value[i];
newWord.appendChild( child );
}
else {
var child = document.createElement( "span" );
child.innerHTML = input.value[i];
newWord.appendChild( child );
}
}
}
}
}
.colored {
color: red;
}
<div id="wordGenerated">illustration</div>
<input id="wordTyped" type="text" />
Here, i am getting the problem to change the fields border color (after validation message) to its (up on filling the text-input) original color.
It is coming like as when i press the next button all the fields color changed to red. Up on filling the field i want to remove this color to white.
Next:- I have to show the error message with the border color also.
e.g. for all fields there should be message like (Incomplete).
if(oldIndex==0)
{
var $emailv = document.getElementById('user_email').value;
var $passwordd = document.getElementById('chatinput2').value;
var $cpassw = document.getElementById('chatinput3').value;
var fields = document.getElementsByClassName("vikass");
if($emailv=="" && $passwordd == "" && $cpassw == "")
{
for(var i = 0; i < fields.length; i++)
{
if(fields[i].value="" )
{
fields[i].style.border="2px solid red";
}
else
{
fields[i].style.border="";
}
}
}
else if($emailv=="")
{
document.getElementById('status').innerHTML="<img src='/APPEX/appex/wp-content/themes/jobs/images/incorrect_icon.png'> Please Enter the Email";
}
else if($passwordd==""){
document.getElementById('user_pass').innerHTML="<img src='/APPEX/appex/wp-content/themes/jobs/images/incorrect_icon.png'> Please Enter the Password";
}
else if(cpassw=""){
document.getElementById('u_c_pass').innerHTML="<img src='/APPEX/appex/wp-content/themes/jobs/images/incorrect_icon.png'> Please Enter the Confirm Password";
}
else if($passwordd != $cpassw){
document.getElementById('u_c_pass').innerHTML="<img src='/APPEX/appex/wp-content/themes/jobs/images/incorrect_icon.png'> Password don not match";
}
else{
if (index >= 0 && index < state.stepCount && !(options.forceMoveForward && index < state.currentIndex))
{
var anchor = getStepAnchor(wizard, index),
parent = anchor.parent(),
isDisabled = parent.hasClass("disabled");
// Enable the step to make the anchor clickable!
parent._enableAria();
anchor.click();
// An error occured
if (oldIndex === state.currentIndex && isDisabled)
{
// Disable the step again if current index has not changed; prevents click action.
parent._enableAria(false);
return false;
}
return true;
}
return false;
}
}
I'm making a register page using HTML, CSS and JS and Java servlet etc. I have a monitorer() function which checks if the user has finished inputting everything before making the register button visible. But now everything works, but somewhere am getting screwed over and the button never comes back..
my button in reg.html :
<input type="submit" value="Register" class="btnSub" id="btnReg" style="visibility:hidden;"/>
javascript function monitorer()
function monitorer() {
var btnReg = document.getElementById("btnReg");
btnReg.style.visibility = "hidden";
var flag = true;
if (document.getElementById("fname").value.length >= 3) {
if (document.getElementById("lname").value.length >= 3) {
if (valiDate(document.getElementById("dob"))) {
if (document.getElementById("USN").value.length == 10) {
if (document.getElementById("passw").value.length > 5) {
var ticks = document.getElementsByClassName("checker"), i = 0;
for (i = 0; i < ticks.length; i++) {
if (ticks.item(i).innerHTML == "✔") {
alert("i val = " + i);
continue;
} else {
flag = false;
break;
}
}
}
} else {
flag = false;
document.getElementById("USN").focus();
}
} else {
flag = false;
document.getElementById("dob").focus();
}
} else {
flag = false;
document.getElementById("lname").focus();
}
} else {
flag = false;
document.getElementById("fname").focus();
}
if (flag == true) {
btnReg.style.visibility = "visible";
} else if(flag == false) {
btnReg.style.visibility = "hidden";
}}
And to help you get as good a picture as you can, a screenshot
See - all the ticks are there, the first name, last name etc are having value.length >=3 but still the register button doesn't show..
Also, I have put the monitorer() method in every input's "onBlur", "onChange" events.
Here is a link to my html file >>> reg.html
and please let me know if i can improve anything?