Recently I have been working on a "spinner" that increases and decreases a number by 1 each time, however I've wanted to add validation to the program so that integers only are accepted (no decimals) however I've been unsuccessful in doing this.
I've researched the use of NaN and parseValue(s) but I've not found a way of including this to my script, and any help would be highly appreciated. All code in the example given works as I want it to, therefore I only need the validation.
CODE: HTML
<!DOCTYPE html>
<html>
<head>
<h1>Spinners in JavaScript</h1>
</head>
<body>
<p id="textDisplay()">0</p>
<div align="middle">
<button onclick="spinUp()">+1</button>
<button onclick="spinDown()">-1</button>
</div>
</body>
</html>
JavaScript
currentNumber = 0;
function spinUp() {
if(currentNumber==100){
currentNumber = 0;
document.getElementById("textDisplay").innerHTML = currentNumber;
} else if(currentNumber < 100) {
currentNumber++
document.getElementById("textDisplay").innerHTML = currentNumber;
}
}
function spinDown() {
if(currentNumber>0){
currentNumber--;
document.getElementById("textDisplay").innerHTML = currentNumber;
} else if(currentNumber<=0){
window.alert("Too low! Higher!");
currentNumber++;
document.getElementById("textDisplay").innerHTML = currentNumber;
}
}
You could use a method like this:
if (number != Math.round(number)){
alert("Enter a whole number");
}
You can use the === operator as below :
if (data === parseInt(data, 10))
alert("data is integer")
else
alert("data is not an integer")
How to check if a variable is an integer in JavaScript?
v === v | 0;
this is true if v is an integer, false otherwise.
Related
I solved the issue. The test cases kept on failing probably because there was a try catch block that needed to be implemented. I completely forgot about that. The test cases worked when I added the try catch block.
Thanks for all the suggestions.
Problem Statement: I need to design a simple html form that takes a limit as input and displays the first given number of the Fibonacci series.
for eg. if 5 is given as input it displays: 0 1 1 2 3
if 8 is given as input it displays: 0 1 1 2 3 5 8 13
But I keep on getting this error:
testFiboForNonZeroPositiveInput:
Check for the logic and check if the correct output is displayed in div with id 'result'
testFiboForZeroInput:
Check for the logic and check if the correct output is displayed in div with id 'result'
TEST CASE FAILED
Here is my code:
function getFibonacci(){
var fib=document.getElementById("fibo").value;
var text;
var arr=[];
if (fib.length===0){
text="Please, specify a number.";
document.getElementById("result").innerHTML = text;
}
else if (fib<0){
text="Please, specify a positive number.";
document.getElementById("result").innerHTML = text;
}
else{
var n1 = 0, n2 = 1, nextTerm, i;
for (i = 1; i <= fib; i++) {
arr.push(n1);
nextTerm = n1 + n2;
n1 = n2;
n2 = nextTerm;
}
var newStr = arr.join(' ').trim()
document.getElementById("result").innerHTML=newStr;
}
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Fibonacci Series</title>
<script src="script.js"></script>
</head>
<body>
<form onsubmit=" return getFibonacci()">
<label for="Enter the number to get a fibonacci">Enter the number to get a fibonacci</label>
<input type="number" id="fibo" name="fibo"><br>
<input type="submit" value="Get Fibonacci Numbers" id="fibobtn">
<div id="result"></div>
</form>
</body>
</html>
Everything seems to work fine and I get the Fibonacci series and the other messages as required but my test cases fail due to this error. Please tell me what to do to fix this issue.
I made these changes to the code and the test cases worked:
(Added a required try catch block)
function getFibonacci(){
try{
var fib=document.getElementById("fibo").value;
var text;
var arr=[];
if (fib.length===0){
text="Please, specify a number.";
document.getElementById("result").innerHTML = text;
}
else if (fib<0){
text="Please, specify a positive number.";
document.getElementById("result").innerHTML = text;
}
else if(fib>0){
var num1=0;
var num2=1;
var nextterm;
var i=0;
for (i = 0; i < fib; i++)
{
arr.push(num1);
nextterm=num1+num2;
num1=num2;
num2=nextterm;
}
var newStr = arr.join(' ');
document.getElementById("result").innerHTML=newStr;
}else {
text="0";
document.getElementById("result").innerHTML = text;
}
}
catch(err){
document.getElementById("result").innerHTML=err;
}
return false;
}
A for attribute on label must by referencing to an id.
<input type="number" id="fibo" name="fibo">
<label for="fibo">Enter the number to get a fibonacci</label>
How do I go about nesting an If/Else statement into a function and then calling that function using a user input in the body in order to make the function calculate the correct alert with JavaScript? I'm missing the knowledge of how to call the statement in the body it seems. Any help would be appreciated! :)
<!doctype html>
<html>
<head>
<title> JavaScript Playground </title>
<script type="text/javascript">
function grade(Grade){
if (Grade <= 90 && Grade >= 100) {
return alert("You made an A!");
} else {
return alert("I don't know what you made!");
}
}
</script>
</head>
<body>
<script>
var Grade = parseFloat(prompt("Please enter a number: "));</script>
</body>
</html>
Several things
Your value cannot be <=90 AND >= 100
No need to return the alert
You need to call the prompt before the grade or move the prompt to the function
Prompt can return empty string, or something not a number so test if it is a number
Your code could be written
function grade(){
var Grade = prompt("Please enter a number: ");
Grade = isNaN(Grade) || Grade.trim()==="" ? 0 : +Grade; // force number if "Not a Number" or an empty string
if (Grade >= 90 && Grade <= 100) {
alert("You made an A!");
} else {
alert("I don't know what you made!");
}
}
grade()
That said,
You should already use eventListeners
It is nicer to use some element's text content than an alert
I also show you a ternary instead of the if (a) text = "a"; else if (b) text = "b" construct
<!doctype html>
<html>
<head>
<title> JavaScript Playground </title>
<script type="text/javascript">
// helper function to make a number from whatever is entered
const makeNum = str => isNaN(str) || str.trim() === "" ? 0 : +str; // convert to 0 if not a number
function grade(Grade) {
Grade = makeNum(Grade); // convert to number
return Grade >= 90 && Grade <= 100 ? "You made an A!" : "I don't know what you made!";
}
window.addEventListener("load",function() { // on page load
document.getElementById("gradeMe").addEventListener("click",function() {
document.getElementById("res").textContent = grade(document.getElementById('grade').value);
})
});
</script>
</head>
<body>
Please enter a number:
<input type="text" id="grade">
<input type="button" id="gradeMe" value="grade me" />
<span id="res"></span>
</body>
</html>
The line directly after
var Grade = parseFloat(prompt("Please enter a number: "));
You can call your function like grade(Grade);
The if/else is completely unrelated to how you call the function but I think the conditional inside your if statement is mixed up. I'm guessing you probably meant for it to be Grade >= 90 && Grade <= 100 rather than Grade <= 90 && Grade >= 100.
I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.
Below is the javascript I am using:
function start()
{
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent()
{
let number = document.getElementById('number');
let liquid = document.getElementById('Bar');
if parseInt(number <= 20)
{
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
}
else if (number >= 21)
{
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
else if (isNaN(number) || number < 0)
{
alert("Invalid Entry. Enter a Number.")
}
}
window.onload = start;
Here is the HTML code that goes with it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ID Check?</title>
<script src="scripts/pt2script.js"></script>
</head>
<body>
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" value="Enter a number...">
<button onclick="toggleContent()" id="button1">Submit</button>
</body>
</html>
You need to get the value from input and convert it to a number by using an unary plus +.
function start() {
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent() {
let number = +document.getElementById('number').value; // take value as a number
let liquid = document.getElementById('Bar');
if (isNaN(number) || number < 0) { // move exit condition to top and exit early
alert("Invalid Entry. Enter a Number.")
return;
}
if (number <= 20) { // condition without parseint
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
} else { // no need for another check
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
}
window.onload = start;
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" placeholder="Enter a number..."><!-- use placeholder -->
<button onclick="toggleContent()" id="button1">Submit</button>
You are attempting to convert a boolean to an integer. This will not work sense (num >= 20) or whatever will evaluate to true or false, and not a number (NaN). You can convert the value to a number before trying to do a logical comparison. I'd do something such as:
$('.btn').on('click', function() {
let val = $('#num').val();
val = parseInt(val);
if(val >= 21) {
$('img').attr('src', '/path-to-soda');
}
else {
$('img').attr('src', '/other-path');
}
});
As soon as an event triggers your number comparison I would instantly convert it to a number (i'm assuming you are using a number input which will do this for you), and then perform the logical operation. If you're using a number input (which again, i'm just assuming), you won't even need to convert the value to a number. That's only necessary if you're using a text input or something along those lines.
So I made this little thing as I am quite new to programming, but when I open it in Chrome, I am able to type input but then nothing happens. Does anyone know how I can fix this code?
Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<b id="bold">Guess:</b> <input type="text" id="guess">
<input type="submit" value="GO!">
<script>
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low +1)) + low;
return number;
}
var number = getRandomNumber(1,10);
var guess = document.getElementById("guess");
for (var i=0;i=0) {
if (guess>number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too high, try lower!";
}
if (guess<number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too low, try higher!";
}
if (guess==number) {
alert("You're correct, the number is "+number+"!!!");
alert("Thanks for playing my game and have a good day!");
}
}
}
startGame();
</script>
</body>
</html>
You've got a lot of problems, starting with a syntax error.
You have a submit button, but no form to submit. You really just need a button. But, even then, you have to set up a click event handler for it.
Then, your loop isn't configured properly.
You also are not accessing the data the user has typed into the textbox correctly - you need to get the value of the element.
Your if statements should be else if.
The b element should not be used just for presentation. HTML is a "semantic" language, meaning that you use a tag to describe the meaning (not presentation) of an element. For styling use CSS.
See comments inline below for details.
/* CSS is for presentation, not HTML */
#bold { font-weight:bold; }
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<!-- Don't use HTML for styling, use it for semantics. -->
<span id="bold">Guess:</span> <input type="text" id="guess">
<!-- You need a <form> if you have a submit button. For this, you just want a button. -->
<input type="button" value="GO!" id="go">
<script>
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low + 1)) + low;
return number;
}
var number = getRandomNumber(1,10);
var guess = document.getElementById("guess");
// Get a reference to the output area just once
var output = document.getElementById("bold");
// Give the user 3 tries. Your loop wasn't configured properly.
for (var i=0; i < 3; i++) {
// You want to access the data in the textbox. That's the value
// Also, if the first condition isn't true, try the next and so on.
// This is done with else if branches
if (guess.value > number) {
output.textContent = "You're too high, try lower!";
} else if (guess.value < number) {
output.textContent = "You're too low, try higher!";
} else if (guess.value == number) {
alert("You're correct, the number is "+number+"!!!");
alert("Thanks for playing my game and have a good day!");
break; // Get out of the loop because the game is over.
}
}
}
// Set it up so that clicks on the button run the function
document.getElementById("go").addEventListener("click", startGame);
</script>
</body>
</html>
you have some errors:
this doesnt work, it wont loop. actually, why do you want to loop?
for (var i=0;i=0) {
this will run the function once, this means when the user writes the value it wont be checked
startGame();
the button doesnt do anything, also it has a submit and you don't have any forms:
input type="submit" value="GO!">
on each if, the conditions are exclusive, use if/else
below is a working code:
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<b id="bold">Guess:</b> <input type="text" id="guess">
<input value="GO!" onclick="checkGuess()">
<script>
var number = 0;
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low + 1)) + low;
return number;
}
number = getRandomNumber(1, 10);
}
function checkGuess() {
var guess = document.getElementById("guess").value;
if (guess > number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too high, try lower!";
} else if (guess < number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too low, try higher!";
} else if (guess == number) {
alert("You're correct, the number is " + number + "!!!");
alert("Thanks for playing my game and have a good day!");
}
}
startGame();
</script>
</body>
</html>
Although i have no idea about what your program does. you have a syntax error at
for (var i=0;i=0) {
and also you should bind an event to that button rather than doing a submit.
I want to check if input text (amount) is between 1-100 or not but regex test not working.
here is my JS code
<script type="text/javascript" >
console.log(document.getElementById("amount").value); // 222
var regex = /^(100)|[1-9]\d?$/;
if(regex.test(document.getElementById("amount").value))
{
alert('validated')
}
else
alert('error')
</script>
Wrap the code in DOMContentLoaded event callback
Don't use RegEx. Use comparison operators
Code:
document.addEventListener('DOMContentLoaded', function () {
// Get the value & convert it into Number
var value = parseInt(document.getElementById('amount').value, 10);
// Value between 0 & 100
if (value > 0 && value <= 100) {
alert('Valid');
} else {
alert('Error');
}
});
It would be enough to use parseInt() function or Number constructor to perform such a simple validation:
<script type="text/javascript" >
var amount = Number(document.getElementById("amount").value); // 222
alert ((amount > 0 && amount <= 100)? 'Valid' : 'Invalid');
</script>
If you really want to use regex, this should work:
/^100$|^[1-9]\d?$/
It doesn't allow eg 09, but maybe that's OK.
<html>
<head>
<script>
function validateValue()
{
var amount = document.getElementById('testId').value;
if((isNaN(amount ))){
document.getElementById("errorId").style.display= "";
}
else
{
if(amount>100){
document.getElementById("errorId").style.display= "";
}
else
{
document.getElementById("errorId").style.display= "none";
}
}
}
</script>
</head>
<body>
Enter 1 to 100:<input type="text" onkeyup="validateValue()" id="testId"/>
<span id="errorId" style="color:red;display:none"> Not a valid amount</span>
</body>
</html>