Promt to innerhtml - javascript

Im making a bot that is succeding to take orders with alerts and prompts. But now I want to instead show it directly on the page. Does anyone know how I can change the prompts to innerHTML in the code, and still manage to make everything function (and continusly going to the next question)?
This is my code:
// Iteration 2
alert(`Hey! Happy to serve you pizza. On our menu we have ${vegetarian.toLowerCase()}, ${hawaiian.toLowerCase()} and ${pepperoni.toLowerCase()} pizza.`)
// Iteration 3 & 5
let orderName = prompt("Enter the name of the pizza you'd like to order today.").toLowerCase()
console.log(`orderName = ${orderName}`)
let orderQuantity
while(true) {
if (checkOrderName(orderName)) {
console.log("Right type of pizza")
orderQuantity = prompt(`How many ${orderName} pizzas do you want?`)
break;
} else {
console.error("Wrong type of pizza")
orderName = prompt(`we don't have ${orderName} on the menu. Please choose something from the menu:`)
}
}
console.log(`Exited while loop. orderQuantity = ${orderQuantity}`)
// Iteration 4
let orderTotal = calculatePrice(orderQuantity, pizzaPrice)
console.log(`orderTotal = ${orderTotal}`)
// alert("Great I'll get started on your " + orderName + " right away. It will cost " + orderTotal + " kr. It will take " + cookingTime(orderQuantity) + " min.")
document.getElementById("pop-up-replacement").innerHTML = `Great I'll get started on your ${orderName} right away. It will cost ${orderTotal} kr. It will take ${cookingTime(orderQuantity)} min.`
```

Basically, what you need to do is have an html element in which you can display your message / question. Then add an input element so that users can type in their response.
Example html
<h2 id="message"></h2>
<input id="input" />
<button id="submit">Submit</button>
Then using JavaScript you can display the message by changing the innerHTML of the message element. Then when the user clicks the submit button, use the value of the input to collect their answer.
Note: This method is asynchronous, so you will have to use the addEventListener to capture clicks, unlike prompt, which pauses the execution of any JavaScript until the user has exited the prompt.

Related

Manipulating arrays and appending strings in complicated ways

I am some what a beginner in jquery/javascript. I am familiar with how it works, but its been a minute since I have worked with it and recently i've been tasked with something that I think jquery/html would be best for.
So I have a list of 500 refund numbers, i put them into a text box, click a button, and they currently go into an array, I know this works as when I alert the array, I see my values.
What I need some guidance with is how can I take the numbers in this array and make it populate a textbox that looks like the below.
send "REFUNDNUMBER1<f1>" #This is our refund number
send "5<f1>" # This LINE will come after every single refund number
So as you can see, i need to append : send " to the front of the refund number, and " to the end of it and then add send "5" to the line beneath it.
Essentially I am trying to generate a script for someone and if this is the wrong place for help I apologize sincerely, I just need some solid direction so that I can understand what I need to do and how to do it. I have very minimal experience with for loops and arrays unfortunately. and javascript for that matter.
Below is my html code/jquery
<div class="home-content">
<div class="home-heading">
<h1><em>Accounting</em> Void Refund Script Generator</h1>
</div>
<div class="row">
<div class="col-md-8">
<form>
Refund Numbers<br>
<textarea cols="38" rows="27" name="refundNumbers" id="refundNumberstxt"> </textarea>
</form>
</div>
<div class="col-sm-4">
<input type="text" name="companyNumb" size="2">
<button type="button" class="btn" id="generateButton">Generate Scripts</button>
</div>
</div>
</div>
$(document).ready(function(){
$("#generateButton").click( function(){
var txtRefundNumbers = $("#refundNumberstxt").val();
var arrayRefundNumbers = txtRefundNumbers.split('\n');
var msg = ""
var arrayVoidRefundsOutput = arrayRefundNumbers.map(function(x) {
for (var i = 0; i < arrayRefundNumbers.length; i++) {
return 'send "' + arrayRefundNumbers [i] + '"\nsend "5"\n';
}
}).join('');
alert(arrayVoidRefundsOutput)
for (var i = 0; i < arrayVoidRefundsOutput.length; i++) {
msg += arrayVoidRefundsOutput + "\n";
}
});
});
The html and jquery are in their own files fyi.
with the help of irkeninvader i was able to get this. I now get this
send "1"
send "5"
send "1"
send "5"
send "1"
send "5"
send "1"
send "5
which is not what im looking for and I am confused,
map lets you modify each value in an array. You should be able to use this to add text to the beginning and end of each refund number.
After using map to add the appropriate text, use join to create one long string again as your output.
var output = textread.map(function(refundNum) {
return 'send "' + refundNum + '"\nsend "5"\n';
}).join('');
I assume I didn't get that quite right but you should be able to modify it to get the correct text before and after each refund number.
The output variable should now contain your result. Do whatever you need to with it (put its contents into another texteara, log/alert it, etc).
That would make your click handler look like this:
$("#generateButton").click( function(){
var txt = $("#refundNumberstxt").val();
var textread = txt.split('\n');
var output = textread.map(function(refundNum) {
return 'send "' + refundNum + '"\nsend "5"\n';
}).join('');
alert(output);
});

How can i get my numbers and fortunes to show on this script on button click

looking to have the user click the button and have the fortune be selecting randomly and shown on the screen with random numbers from 1-100 underneath them. but i can't seem to get everything to display. :(
<script type = "text/javascript">
var quotes = new Array(16) // Add your quotes below
quotes[0]="Your talents will be recognized and suitably rewarded.";
quotes[1]="He who hurries cannot walk with dignity.";
quotes[2]="Your success in life must be earned with earnest efforts.";
quotes[3]="You love peace.";
quotes[4]="A friend asks only for your time and not your money.";
quotes[5]="You will soon inherit a piece of land.";
quotes[6]="Your luck is about to change.";
quotes[7]="Things will soon go your way.";
quotes[8]="He who stands on toilet is high on pot.";
quotes[8]="Everybody is ignorant, only on different subjects.";
quotes[9]="Fortune favors the brave.";
quotes[10]="There is nothing permanent except change.";
quotes[11]="You haven't failed until you give up.";
quotes[12]="Your ability to juggle many tasks will take you far.";
quotes[13]="Broke is only temporary; poor is a state of mind.";
quotes[14]="Begin nothing until you have considered how it is finished.";
quotes[15]="A huge fortune at home is not as good as money in use.";
function showFortune() {
var space = (' ') // Spacer for between numbers
var rand_inta = Math.floor(Math.random()*100); // Get first number
var rand_intb = Math.floor(Math.random()*100); // Get second number
var rand_intc = Math.floor(Math.random()*100); // Get third number
var rand_intd = Math.floor(Math.random()*100); // Get fourth number
var rand_inte = Math.floor(Math.random()*100); // Get fifth number
var rand_int = Math.floor(Math.random()*16); // Get a number for picking the quote
document.getElementById(fortuneArea).innerHTML=(quotes[rand_int]); // Put the quote in the box
}
</script>
<form action="">
<input type="button" value="Show my fortune!" onclick= "showFortune();" />
</form>
<div id="fortuneArea"></div>
document.getElementById('fortuneArea').innerHTML=(quotes[rand_int]);
Just add single quotes to id name....

Uncaught typeError undefined is not a function

I debugged my code plenty, but I am still having issues. This is a class assignment and I asked my professor and he is stunned as well. I am certain that fixing this error will help me with my code, but what I got wrong I am not sure. Could you help? Here is the error
Here my html code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Magic Word - Sample</title>
<script src="magicWord.js"></script>
</head>
<body>
<div>
<h2 align="center">WELCOME TO MAGIC WORD!</h2>
<h3>Please enter your guess on the space below:</h3>
<div>
<input type="text" id="guestGuess" />
<input type="submit" id="submitButton" onclick="javascript:enteredGuess();" />
</div>
</div>
<div>
<h3>Your guesses so far are: </h3>
<div id="userGuesses"></div>
<div>You have guessed: <span id="userAttempts"></span> times</div>
</div>
</body>
</html>
Here is my Javascript
var numOfAttempts = 5;
var numOfGuesses = 0;
var magicWord = "Just";
function guessesUsed(attemptsTaken) {
var numGuessesLeft = document.getElementById("userAttempts");
numGuessesLeft.innerHTML = attemptsTaken;
}
//function guessesLeft(attemptsLeft) {
// var numGuessesUsed = document.getElementById("guessesLeft");
// numGuessesUsed.innerHTML = attemptsLeft;
//}
function listWordsUsed(wordUsed) {
var userTrials = document.getElementbyId("userGuesses").innerText;
var divisor = document.createElement("div");
divisor.innerHTML = "<div id=" + wordUsed + ">" + wordUsed + "</div>";
userTrials.appendChild(divisor);
return;
}
function enteredGuess()
{
//A user will enter a word and the word will be checked against the magic word
//var enterGuess = prompt("What is your guess?", "Enter your guess here");
var theGuess = document.getElementById("guestGuess");
var magicWordResult;
// Used lower case for both instances to compare both words
if (theGuess.value.toLowerCase() == magicWord.toLowerCase())
{
//The user guesses the correct word
magicWordResult = "Your guess was" + theGuess + "! Nice going!";
//document.writeln("Your guess was: " + guestGuess + "\nand the magic word is " + magicWord);
}
else //The user guesses wrong
{
//When user gets it wrong increase by one the numOfGuesses
numOfGuesses ++;
magicWordResult = "Your guess was" + theGuess + ". Nice try, but that's wrong, try again. \nYou have used " + numOfGuesses + " guesses.";
// Subtract the amount of guesses from the amount of attempts
var guessesLeft = numOfAttempts - numOfGuesses;
if (numOfGuesses == numOfAttempts)
{
// When the user has reached all its attemps
magicWordResult = "Sorry, you ran out of guesses. The magic word was " + magicWord + ".";
}
else
{
magicWordResult = "You still have " + guessesLeft + " guesses left.";
}
//To show the number of guesses the user has used
guessesUsed(numOfGuesses);
//To show the number of guesses the user has left
//guessesLeft(guessesLeft);
//Creates a list of the words used by the user
listWordsUsed(theGuess);
}
// Display in an alert mode and show how the user is doing
alert(magicWordResult);
}
Where is my error?
This:
var userTrials = document.getElementbyId("userGuesses").innerText;
gets the text of the "userGuesses" element as a string, but here:
userTrials.appendChild(divisor);
your code treats it as if it were a DOM node. Because there's no "appendChild" property on a String instance, it's undefined, and that explains the error — you're trying to make a function call but the function reference is undefined instead.
edit — oh also that typo in "getElementById()" is also important, as noted by crclayton in a comment. I missed that one :) The general trick to dealing with the
undefined is not a function
error is to try and find a place where your code might come up with undefined instead of a reference to a function. The primary causes, in my experience, are:
Typos, like the "getElementbyId" thing. If the function name is misspelled, JavaScript won't understand that and so it can't give a better error.
Unsatisfied assumptions about what a variable or property refers to, as in the userTrials variable.
Assumption that some function returns a reference to a function, when it in fact (might) return undefined

jQuery Error - Generating undefined

So I have a list of users registered on my site in 1 column, in the 2nd is their email address with a checkbox next to it. On this page a user can check the box (or multiples) and click a submit button. Once they do that it will generate a list of the emails semicolon separated.
My issue is after they hit submit the lists generates, but the first email address has "undefined" written right next to it.. so instead of saying "domain1#test.com; domain2#test.com" it reads "undefindeddomain1#test.com; domain2#test.com".
Here is my jQuery:
jQuery(document).ready(function() {
jQuery('#memberSubmit').click(function() {
var emailList;
jQuery('.email-members input:checked').each(function() {
var $this = jQuery(this);
emailList += $this.next('a').html() + "; ";
});
jQuery('.email-message').hide();
jQuery('.email-members').hide();
jQuery('.email-checks').hide();
jQuery('#memberSubmit').hide();
jQuery('.email-results a').attr('href', "mailto: " + emailList).fadeIn(2000);
jQuery('.email-results .email-list p').html(emailList).fadeIn(2000);
jQuery('.email-results h2').fadeIn(2000);
jQuery('.email-results p').fadeIn(2000);
jQuery('.email-list h2').fadeIn(2000);
//console.info('Emails: ' + emailList);
});
});
I think my error is on the line: emailList += $this.next('a').html() + "; ";
But I am not sure... any ideas?
Thanks!
Initialize the emailList the variable first, that means it doesn't start at undefined when you perform your first go around. Coincidently, when you're calling += for the first time, it's actually converting undefined to a string, thus meaning your string always starting with that.
var emailList = "";
Try replacing emailList's declaration with this code:
var emailList = "";
That's because emailList starts out as undefined if you don't initialize it. Therefore undefined + "this is a test" would turn out as undefinedthis is a test.

How to display delete message in correct table row?

Below is a function where it controls whatever happens after a file has finished uploading in its own table row. Each table row consists of a file input where the user can upload a file and then the name of the file is appended within it's own table row.
If the upload was successful then it displays a successful message, if upload was not successful then it displays a message stating there is an error. But I also have another function within the function where the user can delete a file by clicking on the "Delete" button. The only problem I have is with this line of code:
$(".imagemsg" + counter).html(data);
Let's say that I have 2 table rows, and I delete a file in the first row, the message within .imagemsg should only be displayed in the first row as that was the row the deletion occured, it shouldn't display the message in the first and second row.
Another example is that if I have 4 table rows and I delete the file in the third row, then the message should be displayed in the 3rd row as that is where the deletion has occured.
So my question is what do I need to add to $(".imagemsg" + counter).html(data); so that the message is only displayed within the row the deletion of the file occured and not in all .imagemsg which is in every row?
Below is full code:
function stopImageUpload(success, imagefilename){
var result = '';
var counter = 0;
counter++;
if (success == 1){
result = '<span class="imagemsg'+counter+'">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
}
else {
result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
var image_file_name = $(this).attr('image_file_name');
jQuery.ajax("deleteimage.php?imagefilename=" + image_file_name)
.done(function(data) {
$(".imagemsg" + counter).html(data);
});
$(this).parent().remove();
});
return true;
}
BELOW IS HTML CODE:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><p class='listImage' align='left'></p>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
I believe that your counter variable will always be 1. So, all your span.imagemsg1 are the same. This is why you get the message in every row. Set the counter outside the function to increment the counter.
I believe that will stop the behavior that you are seeing, but I would like to give a shout out to the other answers as they are giving good advice to cleaning this code up.
Frankly, you should never use unique identifier in the class. Why not use an id or a data-image-count attribute?
In your html code you'll need to add a unique identifier, I would suggest using id. This way when you try to reference the element to add the error message in, it will only find one element. Currently it's looking for the first occurrence of the element with class = "imagemsg". You'll need a way to loop through each "row" and make the id's "imagemgs1", "imagemsg2", etc...Hope it helps.
It would be helpful to be able to see the HTML. Also, I cannot see in your script what you do with the "result" value. At this stage, I personally don't think there is enough info to help satisfactorily you yet.
However, an issue you will undoubtedly see is with your "counter" variable. Maybe that is your problem - hard to tell without the detail I asked for above. Your jQuery.ajax call will complete at some point but the value of "counter" may not be the same as when you called the jQuery.ajax() method. This is because the "counter" variable is being declared in a different scope.
E.g. Look at the code below. It sort of demonstrates your problem with the counter variable. It may look like at the end of 5 seconds it will spit out the numbers from 1 to 10 but it won't. It will spit out the value "10" ten times.
var x = 0;
for (var i = 0; i < 10; i++)
{
x++;
setTimeout(function() { console.log(x); }, 5000);
}
This problem applies to your code as well. You can fix the above by copying the variable value in to a variable of your local scope. E.g.:
var x = 0;
for (var i = 0; i < 10; i++)
{
var newScope = function() {
x++;
var y = x;
setTimeout(function() { console.log(y); }, 5000);
}();
}

Categories