How to display the user's data with calculations - javascript

I'm very new to HTML and especially JavaScript and I already have troubles.
How could I display all the data I took from the user taken through promt.
nothing seems to work from what I know.
here is the code.
function myFunction() {
var userinput;
var userName = prompt("Please enter your name to proceed");
if (userName == true)
{
document.write ("Welcome to Office Cheapo, "+ userName + ". Here is your invoice:");
}
var notebook = prompt("How many notebooks do you want to buy?" , "1 to 10");
if (notebook == true){
document.write ("Notebooks bought -- "+ notebook);
}
var pens = prompt("How many pens do you want to buy?", "1 to 10");
if (pens == true){
document.write ("Pens bought -- "+ pens);
}
var usb = prompt("How many USB Flash Drives do you want to buy?", "1 to 10");
if (usb == true){
var taxusb = (usb*6.75)*0.05;
}
document.write ("USBs bought -- "+ usb);
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cheapo Order</title>
</head>
<body>
<div>
<button onclick="myFunction()">Make an order</button>
</div>
</body>
</html>

userName will either be a string or null (if the user canceled the prompt). So username == true will always be false and your document.write will never be executed.
What you might want is:
if (userName) {
This will execute your block provided that userName is not a falsy value.
The following are all falsy values:
null
undefined
0
""
false
NaN
So as long as the user enters something and presses OK in your prompt, the condition will be met and your code within the if branch, executed.

Related

How to call a function containing If/Else using User Input in JavaScript

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.

JQuery random number guessing game: loop woes

I am trying to make a simple number guessing game: a random number between 1 and 9999999999 is generated and printed to the console. I want the user to input their guess in a form - and keep looping guesses until the guess matches the random number.
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Number Guess</title>
</head>
<body>
<!--text display/button -->
<p>Try and "guess" the random number! Click "Generate new random number" to start"</p>
<div id="out1"></div>
<form id="promptUser">
Your guess:
<input type="text" id="inUserGuess">
<input type="submit" value="Submit">
</form>
<br>
<button id="btn1">Generate new random number</button>
<div id="in1"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>/*SEE SCRIPT BEOW */</script>
</body>
</html>
And here is the javascript/jquery inside:
$(document).ready(function() {
/*initialize random number*/
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum);
var win = false;
while (win = false) {
$('#promptUser').on('submit', function(e){
e.preventDefault;
var userGuess = $('#inUserGuess').val();
console.log("User guess:" + userGuess);
});
/*yes: "congrats! start again"*/
if (userGuess == randNum){
console.log("User guess is correct");
alert("You got it! Try another round.");
win = true;
}
/*no: "not quite. guess again."*/
else {
console.log("user guess is incorrect");
alert("Not quite. Guess again.");
win = false;
}
}
In order to keep the user guessing until they get it right, I put the guess input inside a while loop and used and if/else statement to determine whether their guess matches the random number.
It seems as though the code gets messed up somewhere before the if/else statement- the console log never shows up. Instead, a new random number is generated when submit is pressed.
I know the syntax of gathering input works - before I attempted to give the user infinite guesses the if statement ran fine (though a new random number was automatically generated after each "play", regardless of correct/incorrect guess)
I feel stupid asking this - but I've been fiddling with it for hours.
[[EDIT]] I now have the submit button event handler doing two things: storing the user input to userGuess and checking to see whether or not it matches randNum, but still is stuck in an infinite loop:
<script>
/*initialize random number*/
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum);
var userGuess = "";
do {
$(document).ready(function() {
$('#promptUser').on('submit', function(e){
e.preventDefault;
userGuess = $('#inUserGuess').val();
console.log("User guess:" + userGuess);
if(userGuess == randNum){
console.log("user guess is correct");
alert("That's right! Play again.");
}
else{
console.log("user guess is incorrect");
alert("Not quite. Guess again.");
}
});
});
}
while (userGuess != randNum);
/*generate new random number each on button click */
$('#btn1').on('click', function(){
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum); /*(return random number to console for cheating)*/
});
</script>

My JavaScript username and password won't work

I am new to JavaScript and this site, and I am trying to make a mock up username and password log in and creator. For now, the username and password creator is limited to pre-made username and passwords. The idea is to be able, in the end, to create a username and password on one page then to send that array of usernames and passwords to the log in page. I know the security is bad and I won't use this in a real website, but aside from that, I can't get the code to run. The code outputs username and password text boxes to put in values, but when you click the button to posses them nothing happens. What did I do wrong? Thanks for helping!
The page where the pre-made usernames and passwords are declared:
<!DOCTYPE html>
<html>
<head>
<title>
create account
</title>
<script>
sessionStorage.setItem( "username1", ["bob", "sam"]);
sessionStorage.setItem( "password1", ["lol", "jk"]);
</script>
</head>
<body>
</body>
</html>
The place where the username and password arrays are sent and processed in the log in:
<!DOCTYPE html>
<html>
<head>
<title>
log on page
</title>
<script type = "text/javascript">
var count = 2;
function validate() {
var un = document.getElementById("username").value
var pw = document.getElementById("pword").value
var valid = false;
var unArray = sessionStorage.getItem("username1");
var pwArray = sessionStorage.getItem("password1");
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
window.location = "http://www.google.com";
return false;
}
var t = " tries";
if (count == 1) {t = " try"}
if (count >= 1) {
alert ("Invalid username and/or password. " +
"You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}
else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}
}
</script>
<!--this-->
<style>
p.log_on{
position: fixed;
top: 30px;
left: 20px;
}
</style>
</head>
<body>
<!--here-->
<form name = "myform">
<p class="log_on">
ENTER USER NAME <input type="text" id="username"><br><br><br><br><br>
ENTER PASSWORD <input type="password" id="pword">
<input type="button" value="Check In" name="Submit" onclick="validate()">
</p>
</form>
<!--to here-->
</body>
</html>
sessionStorage can only store strings. You are storing the stringified versions of the arrays, and then looping over the characters in them when you pull them back out.
Serialise the data to JSON before storing it, and parse it with a JSON parser when you read it back.

Displaying Messages Without Using Alerts

I am working on a "guess my number" game and have ran into a problem. My game is supposed to select a random integer between 1 and 10 and allow the user to guess until they guess the correct number. After each guess, I'm supposed to display a message telling whether their guess was too high, too low, correct, or if they'd guessed that number before. I had the game working (except for displaying the array of previously guessed numbers) by using alerts to display the whether the user was too high, low, correct, etc like this.
if (guess == this.num) {
alert("Correct! It took you " + turns " tries to guess my number.");
...
}
However, going back over the directions I see that we are not supposed to user alerts or any other kinds of pop-ups. So I need to figure out how to display these messages on the screen rather than in an alert box.
Here is how I've attempted to do this without the use of alerts, but now the game is not working at all (nothing happens when I click either of the buttons):
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Guess My Number</title>
<script type="text/javascript">
var tries = [];
var game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum : function() {
this.num = parseInt(Math.random() * 10) +1;
},
guessNumber : function(guess) {
try {
guess = parseInt(guess);
}
catch(e) {
alert("Enter a guess!");
this.turns++;
return false;
}
if (guess == this.num) {
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.");
alert("Correct! It took you " + this.turns + " turns to guess my number.");
tries.push(guess);
document.querySelector("#tries").textContent = tries.join(', ');
document.getElementById("guess").value = " ";
return true;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
alert("Your guess is too high. Try again.");
document.querySelector("#tries").textContent = tries.join(', ');
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
else if(tries.indexOf(guess) != -1) {
document.getElementById("result").value = "You have already guessed this number. Try again.";
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
else {
document.getElementById("result").value = "Your guess is too low. Try again.";
document.querySelector("#tries").textContent = tries.join(', ');
tries.push(guess);
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
}
};
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
resetGame();
</script>
</head>
<body>
<h1>Would You Like To Play A Game?</h1>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Directions:</h2>
<p>
The game is very simple. I am thinking of a number between 1
and 10. It is your job to guess that number. If you do not guess
correctly on your first attempt, don't worry, you can keep guessing
until you guess the correct number.
</p>
<p>
Your Guess: <input type="text" id="guess" size="10" />
<br />
<input type="button" value="Sumbit Guess" onclick="guessNumber()" />
<input type="reset" value="Reset Game" onclick="resetGame()"/>
</p>
<h3>How Did You Do?:</h3>
<p>
<input type="hidden" id="result" size="20" />
</p>
<h3>Here Are Your Guesses So Far:</h3
</body>
</html>
Is there any simple way to do this. I want the messages to display in a hidden text filed below the heading "How did you do?:" if that makes it a little clearer.
Here is a jsfiddle I made with my most recent code, http://jsfiddle.net/3p3f86fj/6/
You should add a div to your body with a unique ID, like <div id='result'></div> and then in your JS, reference it by getting the document by ID and your functions should change the text of the div to whatever you need it to be. Make a function to change the name if you want to abstract some of the logic away.
It's broken because of this line I believe:
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.");
You have a stray ) at the end.
I'm looking into other issues I see now.

Why does this think it's correct?

I'm new to js and I have this very simple code. It's supposed to be a login, and it's not working. I don't need any tips on making it better, I'm planning to do that when this starts to work.
<!DOCTYPE html>
<head> Sign-in </head>
<body>
<script type="text/javascript">
var em = prompt("Enter E-mail Here:")
if(em = "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa = "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
</script>
</body>
</html>
What it's doing now is no matter what, it thinks that the correct e-mail and password were used. Could somebody help?
I've fixed your code up a bit. Some things to note.
You can't just put raw content in the <head>.
Your password is in the raw source of the page, so anyone can view the page source and see what the correct password is. That's an absolutely horrible design. Passwords should be passed to server side where they're checked for validity.
In C like programming language such as Javascript, == tests for equality and will return a boolean. The = sign assigns a value to a variable.
<!DOCTYPE html>
<head>
<title>Sign-in
</title>
<script type="text/javascript">
var em = prompt("Enter E-mail Here:")
if(em == "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa == "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
</script>
</head>
<body>
</body>
</html>
Just one addition:
== checks value
=== checks value and type
Someone who deactivates js or doesn't support it like curl/wget and others, will not be stopped by this, except you load the whole website with js, what might be stupid cause of search engines might not index the content though.
Hope this helps.
fixed
var em = prompt("Enter E-mail Here:")
if(em === "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa === "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
You use a single = when you're assigning a variable a value. like var x = 1.
But if you want to check equality, use ===. like if(x ===1)

Categories

Resources