Sorry to ask this again, but I wanted to add more code for context.
I am making a rock paper scissors game and want to change the playerChoice key when a button the button is pressed.
I want to add an onclick event to each button and run a function that will set the playerChoice property so it references the gameOptions index.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Lapis, Papyrus Scalpellus</h1>
<h2>Make a Choice</h2>
<button id="Lapis">Lapis</button>
<button id="Papyrus">Papyrus</button>
<button id=Scalpellus>Scalpellus</button>
<h2>Game Results</h2>
<script src="script.js"></script>
</body>
</html>
const gameOptions = ["Lapis", "Papyrus", "Scalpellus"];
const newChoice = randomChoice();
console.log(newChoice);
const humanPlayer = {
playerChoice: gameOptions[0],
};
const computerPlayer = {
playerChoice: randomChoice(),
};
document.querySelector("#Lapis").onclick = function() {
humanPlayer.playerChoice = gameOptions[0];
};
document.querySelector("#Papyrus").onclick = function() {
humanPlayer.playerChoice = gameOptions[1];
};
document.querySelector("#Scalpellus").onclick = function() {
humanPlayer.playerChoice = gameOptions[2];
};
console.log(humanPlayer);
//Random Choice
function randomChoice() {
const theChoice = gameOptions[Math.floor(Math.random() * 3)];
return theChoice;
}
//Players
function resultText(innerText){
const paragraph = document.createElement('p');
paragraph.innerText = innerText;
document.body.appendChild(paragraph);
}
//Outcomes
function fight(){
if(computerPlayer.playerChoice === humanPlayer.playerChoice){
resultText("Its a Tie!20. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if (computerPlayer.playerChoice === "Lapis"){
if(humanPlayer.playerChoice === "Papyrus"){
resultText("Human Player Wins!6. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if( humanPlayer.playerChoice === "Scalpellus"){
resultText("Computer Player Wins!5 You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}
}else if(computerPlayer.playerChoice === "Papyrus"){
if ( humanPlayer.playerChoice === "Lapis"){
resultText("Compter Player Wins!4. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if( humanPlayer.playerChoice === "Scalpellus"){
resultText("Human Player Wins!3. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}
}else if(computerPlayer.playerChoice === "Scalpellus"){
if ( humanPlayer.playerChoice === "Lapis"){
resultText("Human Player Wins!2. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if( humanPlayer.playerChoice === "Papyrus"){
resultText("Computer Player Wins!1. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}
}
}
fight()
You can use the following to keep your code simple:
var btns = document.querySelectorAll("button");
for (var i = 0; i < btns.length; i++){
btns[i].addEventListener("click", btnHandler);
}
And then your handler function will be called each time a button is clicked without the need to repeat your code:
function btnHandler(el){
switch (el.getAttribute("id")){
case "Papyrus":
...
default: break;
}
}
It also allows you to pass the button element itself, so you can just pull out the ID attribute when needed, rather than having to pass a parameter for each different instance across separate calls. For the win condition check, you can eliminate several "if" statements by simply seeing if they're equal, and if they're not, only compare the human choice to the computer choice which would beat it and set the result thusly. It can be optimized further, but I imagine you would like to learn something from this so I've commented the fiddle as well.
For this example, I also moved the fight() function to the button handler so the player would have a choice, and the computer's choice would only be triggered at that point as well. There were a few instances in your original code which called functions and set variables, but didn't use them etc, as well as a few syntax errors.
See attached fiddle:
https://jsfiddle.net/s0toz3L8/2/
Related
I need the input field to clear after the user clicks the button to convert the number they've entered. I'm having a difficult time figuring this out, if anyone can help i feel like it's a very simple solution but, I can't seem to wrap my head around it.
(function () {
//Constants
const KM_TO_MILES = 0.625;
const MILES_TO_KM = 1.6;
var user = prompt("So..What's your name beautiful?");
if (user === null) {
alert("NOOOOO, you cancel me? meanie.")
remove();
}
//on load function
window.onload = function () {
var result = document.getElementById("result");
//display the user's name with a message prompt to continue to enter a distance
result.innerHTML = "Okay, " + user + ", enter your distance and I will calculate for you, don't worry.";
document.getElementById("convertBtn").onclick = startConvert;
};
//on load function done
//conversion function
function startConvert() {
var placeholder = document.getElementById("distance").value;
var distanceInput = document.getElementById("distance").value;
var conversion = document.getElementById('List').value;
document.getElementById("List").value;
// If the user doesn't input a number run the alert
if ((placeholder === "") || (conversion == "Select Types")) {
alert("You didn't enter anything mate");
// If the user inputs a number and clicks KM to M then calculate it and in the html page change the text to show the answer.
} else if (conversion == "Kilometers to Miles") {
document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * KM_TO_MILES + " miles.");
// If the user inputs a number and clicks M to KM then calculate it and in the html page change the text to show the answer.
} else if (conversion == "Miles to Kilometeres") {
document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * MILES_TO_KM + " kilometers.");
}
}
//conversion function done
}());
document.getElementById('yourid').value = '';
you call this event on your button click surely it'll be works
I am trying to figure out if there is a way to access the information stored inside a variable that I defined inside a function? I am kinda confused on how to do what I am trying to do here...
note: this isn't the full code, but the piece of the code I need help with.
let question1 = new Question("What is California State Flower?", "1. Rose. 2. Tulip. 3. Poppy");
firstQuestion();
function firstQuestion(){
let someAnswer = prompt(question1.questionName + " " + question1.questionString);
}
if (someAnswer == "poppy"){
I am trying to use the if statement to figure out if a question answer is correct, but I can't do that because someAnswer was defined inside the function.... and i'm not sure if there is a way to do this without using a function?
Update:
Ok, I got that piece working, but now my code's if/else statement isn't working. if i put in the wrong answer, it says I have the right answer. I don't really see any logical reason for that...
//store score total
let pointsCount = 0;
//questions
class Question {
questionName: string;
questionString: string;
constructor(questionName:string, questionString:string){
this.questionName = questionName;
this.questionString = questionString;
}
}
//question one
let question1 = new Question("What is the California State Flower?", "1. Rose. 2. Tulip. 3. Poppy.");
let firstAnswer = firstQuestion();
function firstQuestion(){
return prompt(question1.questionName + " " + question1.questionString);
}
if (firstAnswer === "Poppy" || "poppy"){
pointsCount ++;
alert("You got it!" + " " + "You now have" + " " + pointsCount + " " + "points!");
} else {
alert("Wrong!" + " " + "You now have" + " " + pointsCount + " " + "points!");
}
//question two
let question2 = new Question("What is the California State Bird?","1. Quail. 2. Eagle. 3. Penguin.")
let secondAnswer = secondQuestion();
function secondQuestion(){
return prompt(question2.questionName + " " + question2.questionString);
}
if (secondAnswer === "quail" || "Quail"){
pointsCount++;
alert("You got it!" + " " + "You now have" + " " + pointsCount + " " + "points!");
} else if (secondAnswer !== "quail" || "Quail") {
alert("Wrong!" + " " + "You now have" + " " + pointsCount + " " + "points!");
}
You're close; you're not returning anything from your firstQuestion function, so nothing's ever really going to happen when you run this.
let question1 = new Question("What is California State Flower?", "1. Rose. 2. Tulip. 3. Poppy");
let answer = firstQuestion();
function firstQuestion(){
// return whatever the user enters in the prompt
return prompt(question1.questionName + " " + question1.questionString);
}
if (answer.toLowerCase() == "poppy"){
// call .toLowerCase on your answer to ensure you've covered capitalization edge-cases
}
Maybe this is what you need
let someAnswer;
function firstQuestion(){
someAnswer = prompt(question1.questionName + " " + question1.questionString);
}
For some reason, the arithmetic in the function updateScore(result) doesn't work properly (the function is called later on in the code). wins, ties and losses are printed as they should, but lives is printed as NaN. I know what NaN means. I've also identified that the variables, for some reason or other, are created as strings. What appears strange to me, is that it's working for four out of five variables. There's no consistency. I've tried some number conversions using Number(lives), but that doesn't work either. Any suggestions to how I can ensure that the variables are created as numbers, and aritmethic operations will work?
var wins = 0,
ties = 0,
losses = 0,
lives = 5,
previouscpuChoice = 0;
$("#startknapp").click(function(){
var spiller = prompt("Hva heter du?");
$("#userSelect").html(userMenu);
$("#result").html("<h4>Velg figur, " + spiller + "</h4>");
$("#status").html('<h4>Liv: <span id="life">' +lives+ '</span> - Seire: <span id="win">' + wins + '</span> - Uavgjort: <span id="tie">' + ties + '</span> - Tap: <span id="lose">' + losses + '</span>');
console.log(typeof "lives");
console.log(typeof "wins");
});
function updateScore(result) {
tie = document.getElementById("tie");
win = document.getElementById("win");
lose = document.getElementById("lose");
lives = document.getElementById("life");
console.log(typeof "wins");
var imgSrc = "images/" + userChoice + "-" + result + ".png";
if (result === "tie") {
ties = ties + 1;
tie.innerHTML = ties;
$('.result-img').attr('src', 'images/tie.png');
}
if (result === "vant") {
wins++;
$('.result-img').attr('src', imgSrc);
}
if (result === "tapte") {
losses++;
lives--;
lose.innerHTML = losses;
life.innerHTML = lives;
$('.result-img').attr('src', imgSrc);
}
};
Have you tried the following?
var tie = parseInt(document.getElementById("tie").value);
Your current code:
document.getElementById("tie")
retrieves the DOM element rather than the value of the input. so you need to use .value and then you parse it as an integer as the inputs value is likely a string representation of the number you want rather than an integer value.
After pondering, I figured it's okay if the variables are strings, and looked at the code from a different perspective. And what do you know, it was a simple bug.
$("#startknapp").click(function(){
var spiller = prompt("Hva heter du?");
$("#userSelect").html(userMenu);
$("#result").html("<h4>Velg figur, " + spiller + "</h4>");
$("#status").html('<h4>Liv: <span id="life">' +lives+ '</span> - Seire: <span id="win">' + wins + '</span> - Uavgjort: <span id="tie">' + ties + '</span> - Tap: <span id="lose">' + losses + '</span>');
console.log(typeof "lives");
console.log(typeof "wins");
});
function updateScore(result) {
tie = document.getElementById("tie");
win = document.getElementById("win");
lose = document.getElementById("lose");
life = document.getElementById("life");
Originally the last line of updateScore(result) was:
lives = document.getElementById("life");
As a result two variables were mixed (the local one for the function (life) and the global one (lives). So in the end it was a typo. However, I'm still intrigued by the fact that a variable can be a string, and the value contained within an integer.
Hi I have 2 html pages that use functions in a single .js file. The second page needs access to data first initialised by the first page when it calls the .js file:
$(document).ready(function()
{
var destinationTo = "";
var departingFrom = "";
var departing = "";
var returning = "";
var numAdults = "";
var numChildren = "";
var travelType = "";
$("#departing").datepicker();
$("#returning").datepicker();
$("#orderTickets").click(function()
{
destinationTo = $("#myDestination option:selected").text();
departingFrom = $("#myDepart option:selected").text();
departing = $("#departing").val();
returning = $("#returning").val();
numAdults = $("#adults option:selected").text();
numChildren = $("#children option:selected").text();
travelType = $("#class option:selected").text();
var item = document.getElementById("hiddenListItem");
if (departing === "" && returning === "")
{
alert("Please enter your travel dates.");
}
else if (item.style.display !== 'none' && returning === "")
{
alert("Please enter a return date.");
}
else if (departing === "")
{
alert("Please enter a departing date.");
}
else
{
if (item.style.display !== 'list-item')
{
var isConfirmed = confirm("Please confirm your travel: outward journey from " + departingFrom + " on " + departing + " to " + destinationTo +
" adults " + numAdults + " children " + numChildren + " travelling in " + travelType + " coach " + "?");
if(isConfirmed == true)
{
window.location.href = 'PersonDetail.html';
}
}
else
{
var isConfirmed = confirm("Please confirm your travel: outward journey from " + departingFrom + " on " + departing + " to " + destinationTo + " returning on " +
returning + " adults " + numAdults + " children " + numChildren + " travelling in " + travelType + " coach " + "?");
if(isConfirmed == true)
{
window.location.href = 'PersonDetail.html';
}
}
}
});
$("#startAgain").click(function()
{
document.getElementById("travelDetailsForm").reset();
});
$("#finish").click(function()
{
var name = $("#name").val();
var addy1 = $("#address1").val();
var addy2 = $("#address2").val();
var addy3 = $("#address3").val();
var email = $("#email").val();
var number = $("#number").val();
travelType = $("#class option:selected").text();
// test
confirm("name " + name + " addy1 " + addy1 + " addy2 " + addy2 + " addy3 " + addy3 + " email " + email + " number " + number + " detion " + destinationTo);
});
});
I want to be able to access the data in the function call "#orderTickets" in the function "#finish" to dispay the order detils to the user etc. I thought I could put the variables in the global position, but think they reset themselves when another page accesses the .js file.
HTML and javascript are not my thing, would appreciate some help with this.
EDIT: the user clicks "order tickets" on html page 1, .js validates page 1 then directs to html page 2, (same .js file) validates page 2 and hopefully displays data collected from page 1 & 2.
You are partly correct when you say that the variables reset themselves. What actually happens is that each page has their own environment, so the variables from the previous page doesn't even exist any longer. Each page gets their own set of brand new variables.
Also, the variables that you have aren't even global in the page. They exist in the scope of the ready event handler. The reason that the variables exist at all after the ready event handler finishes is that they are caught in the closure of the click event handlers.
To keep the values from one page to the next, you have to store them outside of the page itself. You can for example put the values in a cookie, which you then can read in the second page.
I need to write a program for a wedding planner. They wish to create a gift registry for each couple. They want the gifts broken down by the whether the gift giver is on the bride side or groom side. They also know that specific gifts (toasters, silverware, and stemware) tend to be repeated so they want those gifts listed and have the name of the gift giver under them. The repeating gifts are only the ones that have been told you by the client (toasters, silverware, and stemware) they do not want you to determine which gifts repeat, they are just looking for those specific three. So I can implement code for only silverware, stemware, and toasters, which I have this time. But now I cannot get any correct output.
After the program has run, it should have a printout somewhat like this.
Groom side:
Tom: toaster
Bill: silverware
Bob: stemware
Steve: Lexus
Bride side:
Jill: toaster
Suzy: silverware
Pat: stemware
Karen: horse
Multiple toasters by:
Tom
Jill
Multiple silverware by:
Bill
Suzy
Multiple stemware by:
Bob
Pat
Here is what I've got so far...
var guestName;
var gift, side, kind, groomNameAccum, brideNameAccum;
var toaster, silverware, stemware, giftType;
var toasterAccum, silverwareAccum, stemwareAccum;
var noGift = 0;
var groomCounter = 0;
var brideCounter = 0;
//initalizing loop
var guest = "yes";
//start loop
while (guest == "yes") {
side = prompt("Which side are you on? groom or bride?", "");
guestName = prompt("Whats your name?", "");
kind = prompt("What kind of gift?", "");
if (side == "groom") {
groomCounter = groomCounter + 1;
if (groomCounter == 1) {
groomNameAccum = "Groom side: <br>" + groomCounter + ". " + guestName + ": " + kind;
} else {
groomNameAccum = groomNameAccum + "<br>" + groomCounter + ". " + guestName + ": " + kind;
}
} else
if (side == "bride") {
brideCounter = brideCounter + 1;
if (brideCounter == 1) {
brideNameAccum = "<p>Bride side: <br>" + brideCounter + ". " + guestName + ": " + kind;
} else {
brideNameAccum = brideNameAccum + "<br>" + brideCounter + ". " + guestName + ": " + kind;
}
}
if (kind == "toaster")
{
toasterAccum = toasterAccum + "; " + guestName;
}
else if(kind == "silverware")
{
silverwareAccum= silverwareAccum + "; " + guestName;
}else if (kind == "stemware")
{
stemwareAccum = stemwareAccum + "; " + guestName
}
else
{
multiples = 0;
}
guest = prompt("Are there anymore guests?", "yes");
}
document.write(groomNameAccum);
document.write(brideNameAccum);
document.write("<p>Multiple Toasters by:<br>" + toasterAccum + "<br/>");
document.write("Multiple Silverware by:<br>" + silverwareAccum + "<br/>");
document.write("Multiple Stemware by:<br>" + stemwareAccum + "<br/>");
As I was saying, my teacher doesn't try to teach us the shortcuts and easy stuff, because it is a classroom of technical college students. I know there are easier ways to write it out, but I don't know how yet. Hes got his formula for success that always leads me looking for correct answers....