Incorrect return value javascript - javascript

I am trying to create a simple guessing game and my return value or my functionality seems correct. I have console.logged typeof for my input value as well as my randNum value and they are both numbers. However my alert is always incorrect. What am I doing wrong?
var currentGuess = false;
var randNum = Math.floor(Math.random() * 100)
var input = document.getElementById("guess").value;
var input = parseInt(input);
var btn = document.getElementById("submit");
var results = document.getElementById("results");
console.log(randNum);
function check() {
checkNum(input, randNum);
if( input === randNum) {
alert("correct");
} else {
alert("incorrect");
}
}
function checkNum(guess, actualNum) {
currentGuess = false;
if(guess === actualNum) {
return true;
}
return currentGuess;
}
btn.addEventListener("click", check, false);

You didn't take input again when check is called.
just add this in your check function
input = parseInt(document.getElementById("guess").value);
Like this
function check() {
input = parseInt(document.getElementById("guess").value);
checkNum(input, randNum);
if( input === randNum) {
alert("correct");
} else {
alert("incorrect");
}
}

Fiddle with working solution: https://jsfiddle.net/pp9Lrpe6/
You are listening for the click even on the input, but getting the input value when everything is loaded, which is empty - returning input = NaN. This value isn't updated when a user clicks:
var randNum, btn, results;
// Generate random number.
randNum = Math.floor( Math.random() * 100 );
// Submit button to listen for click events on.
btn = document.getElementById( 'submit' );
// Display result one at a time in #results.
results = document.getElementById( 'results' );
// Number to guess.
console.log( 'Random number: ' + randNum );
// Check the input on click of #submit
function check() {
var input = parseInt( document.getElementById( 'guess' ).value, 10 );
if ( input === randNum ) {
results.innerHTML = '<p class="correct">' + input + ' is correct!</p>';
} else {
results.innerHTML = '<p class="incorrect">' + input + ' is not correct!</p>';
}
}
// Add event listener for #submit
btn.addEventListener( 'click', check, false );
As a good practice, you should give you input the type="number".
You should also declare the radix for parseInt (MDN)

try this:
<html>
<head>
</head>
<body>
<input type="text" id="guess"><br>
<input type="button" id="submit" value="check"><br>
<div id="results"></div>
<script>
var currentGuess = false;
var randNum = Math.floor(Math.random() * 100)
var btn = document.getElementById("submit");
var results = document.getElementById("results");
console.log(randNum);
function check() {
var input = document.getElementById("guess").value;
var input = parseInt(input);
if( input === randNum) {
alert("correct");
} else {
alert("incorrect");
}
}
btn.addEventListener("click", check, false);
</script>
</body>

Related

My javascript code is crashing when I put a random number generator/guesser into a function. Why does it crash?

I have build a random number generator used to guess numbers. I have limited this number guesser not to ask the same number twice and this works outside of the function. as soon as I put the number generator/guesser into a function the window crashes every few attempts. I believe this has to do with the number generating on an infinite loop. Can anyone see what the issue is?
Edit: for those who like to see the HTML as well. I have two simple inputs before the JS:
<body>
<p>Think of a number!</p>
<select name="fingers" id="mynumber">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<button id="startguess">Start guessing my number!</button>
Here are the global variables:
var guessed = [""];
var guess = "";
Here is the function:
function doaguess(correctanswer) {
guess = Math.floor(Math.random() * 6);
var n = "";
n = guessed.includes(guess);
if (n == true) {
guess = Math.floor(Math.random() * 6);
} else {
if (guess == correctanswer) {
return (true);
} else {
return (false);
}
}
}
And the rest of the script is this:
document.getElementById("startguess").onclick = function() {
var mynumber = document.getElementById("mynumber").value;
var gotit = false;
var numberofguesses = 1;
while (gotit == false) {
if (doaguess(mynumber) == true) {
gotit = true;
alert("Got it! It was a " + mynumber + ". It took me " + numberofguesses + " guesses.");
} else {
numberofguesses++;
guessed.push(guess);
}
}
}
Everything worked fine until I moved the generator into the function doaguess(). I have tried moving the variables into global from local to change the scope and this made the code work but it now crashes. Any help is appreciated.
Edit: for those who like to see the HTML as well. I have two simple inputs before the JS:
If you guess the number after (n == true) you are not returning anything, and the guess could be a repetead one, that should be into a loop also searching for a new guess. When you guess the number in that case, then the result is not true and the correct answer is added in the guessed array causing the infinite loop.
Fix:
n = guessed.includes(guess);
while (n == true) {
guess = Math.floor(Math.random() * 6);
n = guessed.includes(guess);
}
if (guess == correctanswer) {
return (true);
} else {
return (false);
}
Its this line guessed.push(guess); should be guessed.push(mynumber);
Here is it working:
var guessed = [""];
var guess = "";
function doaguess(correctanswer) {
guess = Math.floor(Math.random() * 6);
var n = guessed.includes(guess);
if (n === true) {
guess = Math.floor(Math.random() * 6);
} else {
return guess == correctanswer;
}
}
document.getElementById("startguess").onclick = function() {
var mynumber = document.getElementById("mynumber").value;
var gotit = false;
var numberofguesses = 1;
while (!gotit) {
if (doaguess(mynumber)) {
gotit = true;
alert("Got it! It was a " + mynumber + ". It took me " + numberofguesses + " guesses.");
} else {
numberofguesses++;
guessed.push(mynumber);
}
}
}
<button id="startguess">Guess</button>
<input id="mynumber" type="number"></input>
I have found the issue. The variables are not resetting every time I try to offer a number so it appears not to work if I try multiple times without reloading the page because the numbers are stored instead of resetting at each new "play". To resolve this I need to reset the variables and arrays guess and guessed every time the onclick is pressed. Like this:
document.getElementById("startguess").onclick = function() {
guessed = [""];
guess = "";
var mynumber = document.getElementById("mynumber").value;
var gotit = false;
var numberofguesses = 1;
while (gotit == false) {
if (doaguess(mynumber) == true) {
gotit = true;
alert("Got it! It was a " + mynumber + ". It took me " + numberofguesses + " guesses.");
} else {
numberofguesses++;
guessed.push(guess);
}
}
}

change radio value with form input

I am trying to change the value of a radio button with a form input: https://jsfiddle.net/91oz4nfL/
Essentially by default I want it to be NO but if the argument is triggered then change the radio button to YES
function calculateBMI() {
var weight = document.getElementById('input1').value;
var height = document.getElementById('input2').value / 100;
var output = document.getElementById('output');
var bmi = ((weight) / (height * height));
var result = ""
if (bmi > 22) {
result = "Change question radio to yes!";
}
bmi = bmi.toFixed(2);
if (bmi && bmi != Number.POSITIVE_INFINITY) {
output.innerHTML = result;
output.style.display = 'block';
} else {
result.innerHTML = '';
output.style.display = 'none';
}
}
document.getElementById('input1').addEventListener('keyup', calculateBMI);
document.getElementById('input2').addEventListener('keyup', calculateBMI);
You simply need to add a few lines in your if statement, like so
if (bmi > 22) {
document.getElementById("Radio9").checked = true;
result = "Change question radio to yes!";
} else {
document.getElementById("Radio10").checked = true;
}
If a radio button is true this means that it is checked. The above code sets the 'Yes' radio button to checked if bmi is greater than 22, otherwise sets the 'No' radio button to true.
https://jsfiddle.net/91oz4nfL/
Try this:
var radioYes = document.getElementById('Radio9');
var radioNo = document.getElementById('Radio10');
var weight = document.getElementById('input1').value;
var height = document.getElementById('input2').value / 100;
var output = document.getElementById('output');
var bmi = ((weight) / (height * height));
var result = ""
debugger
if (bmi > 22) {
result = "Change question radio to yes!";
radioYes.checked = true;
}else{
radioNo.checked = false;
}
https://jsfiddle.net/n820pz3e/1/

How to create prevent default function for input?

When a user enters numeric values I just want to display even number I want to set prevent default on odd values.
HTML:
Enter any number: <input type="text">
<p id="even"></p>
JavaScript:
function (e) {
e.preventDefault();
}
You can add an event listener to the input element and validate that the number is even.
DEMO
JavaScript
var num = document.getElementById('num');
var out = document.getElementById('out');
var isNumber = function(n) { return n == parseFloat(n); }
var isEven = function(n) { return isNumber(n) && (n % 2 == 0); }
var isOdd = function(n) { return isNumber(n) && (Math.abs(n) % 2 == 1); }
var myFunction = function(e) {
var val = num.value;
if (isEven(val)) {
out.innerHTML = val;
} else {
e.preventDefault();
}
};
num.addEventListener('blur', myFunction, false);
HTML
Enter any number: <input type="text" id="num" />
<hr />
Value: <span id="out"></span>
Update
If you want live validation, change blur to keyup.
num.addEventListener('keyup', myFunction, false);
If you are asking how to detect an odd value, you could use something like
function whatever(e){
if(value % 2 != 0){
e.preventDefault()
}else{
//Do something
}
}
Probably something like this:
$("input").mouseup(function() {
var num = $(this).val();
if (num % 2) {
console.log(num);
}
});
EDIT: and here it is in plain JS:
var el = document.getElementsByTagName("input")[0];
el.onkeyup = function () {
var num = el.value;
if (num % 2 == false) {
console.log(num);
}
};

live form results using javascript

I am trying to provide a message below the fields of a form. The message will depend on what is entered in both fields.
How would I go about making it so it calculates in real time using both the fields and passing it through a calculation?
Here is the fiddle http://jsfiddle.net/6qSeH/
I am using this to get the document values
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
and this at the end to run the function
yearCalculator();
There are many missing pieces in your code.
Firstly you have written code entirely using javascript and trying to use jQuery syntax. So how would you expect it to work.
jQuery to set HTML --- msg.html(value);
javascriptto set HTML --- msg.html = value;
Second When you are checking for Not a Number
It is supposed to look like
val1 === NaN // It is not a string
Also this will never work as NaN is never equal to NaN
Use isNaN() method instead
Third
<div class="message"></div>
supposed to be
<div id="message"></div>
Next you need to assign events to your input. Otherwise it would only work when the page loads for the first time..
input1.addEventListener('change', yearCalculator);
input2.addEventListener('change', yearCalculator);
Otherwise it will only work the first time your script loads.
Cleaned up code
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
var msg = document.getElementById('message');
input1.addEventListener('change', yearCalculator);
input2.addEventListener('change', yearCalculator);
function yearCalculator() {
var yearOne = input1.value;
var yearTwo = input2.value;
val1 = parseInt(yearOne);
val2 = parseInt(yearTwo);
if (isNaN(val1) || isNaN(val2)) {
msg.innerHTML = "Please enter a valid year !!";
return;
}
var value1 = yearOne - yearTwo + 18;
if (yearOne == yearTwo) {
msg.innerHTML = "Both years are the same";
}
if (yearOne < yearTwo) {
if (yearTwo < value1) {
msg.innerHTML = "This is a good result";
} else if (yearTwo > value1) {
msg.innerHTML = "This is a bad result";
} else {
msg.innerHTML = "This is neither good or bad";
}
}
else {
msg.innerHTML ="Year 1 is greater than Year 2";
}
};
yearCalculator();
Check Fiddle
You can use onchange="yearCalculator()" in both input fileds
First change the class='message' to id='message'. Then try this code:
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
var yearOne = input1.value;
var yearTwo = input2.value;
var msg = document.getElementById('message');
function yearCalculator(value1, value2) {
msg.innerHTML='';
val1 = parseInt(value1);
val2 = parseInt(value2);
if (val1 === "NAN" || val2 === "NAN") return;
var value1 = val1 - val2 + 18;
if (val1 == val2) {
msg.innerHTML="Both years are the same";
}
if (val1 < val2) {
if (val2 < value1) {
msg.innerHTML = "This is a good result";
} else if (val2 > value1) {
msg.innerHTML = "This is a bad result";
} else {
msg.innerHTML = "This is neither good or bad";
}
}
};
yearCalculator(yearOne,yearTwo);
input1.onkeyup=function() {
yearCalculator(this.value,document.getElementById("input-mini2").value);
};
input2.onkeyup=function() {
yearCalculator(document.getElementById("input-mini").value,this.value);
};

Maximum allowed value for <input type="text"/>

I have this input field:
<input type="text"/>
How can I allow entering only a number that is not greater than some predefined value, like for example 10, so every attempt to enter a number greater than 10 won't be allowed?
Javascript
function createValidator(element) {
return function() {
var min = parseInt(element.getAttribute("min")) || 0;
var max = parseInt(element.getAttribute("max")) || 0;
var value = parseInt(element.value) || min;
element.value = value; // make sure we got an int
if (value < min) element.value = min;
if (value > max) element.value = max;
}
}
var elm = document.body.querySelector("input[type=number]");
elm.onkeyup = createValidator(elm);
HTML
<input type="number" min="0" max="10"></input>
I haven't tested it, but I think it should work.
Convert the value to a number immediately, then compare it to a maximum value:
window.onload = function () {
var textbox = document.getElementById("text1");
var maxVal = 10;
addEvent(textbox, "keyup", function () {
var thisVal = +this.value;
this.className = this.className.replace(" input-error ", "");
if (isNaN(thisVal) || thisVal > maxVal) {
this.className += " input-error ";
// Invalid input
}
});
};
function addEvent(element, event, callback) {
if (element.addEventListener) {
element.addEventListener(event, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + event, callback);
} else {
element["on" + event] = callback;
}
}
DEMO: http://jsfiddle.net/jBFHn/
As you type, if the value isn't a number or the value is greater than the maximum, the "input-error" class is added to the element. You can take out the whole class changing, and put in your own stuff.
This is how I used this property in my project.
<script>
function integerInRange(value, min, max, name) {
if(value < min || value > max)
{
document.getElementById(name).value = "100";
alert("Write here your message");
}
}
</script>
And my input like this
<input type="text" id="yyy" name="xxx" onkeyup="integerInRange(this.value, 0, 100, "yyy")" />
If you using bootstrap you can use alert window!
function integerInRange(value, min, max, name) {
if(value < min || value > max)
{
document.getElementById(name).value = "100";
$.pnotify({ title: 'UYARI', text: 'Girilen değer ' + min + ' ile ' + max + ' arasında olmalıdır.', type: 'error' });
$(".ui-pnotify-history-container").remove();
}
}

Categories

Resources