Javascript random that saves where the random has linked to already - javascript

So I tried writing this question before and it was closed. While I was still able to get comments, I am just assuming that I used up the amount of comments or something. Please, I just need to know how to call the javascript function in a link so that it works. Thank you to the person who provided the code for the function I just need to know how to call to it in a link. Nothing I have tried works. I have tried other javascript function searches and none of that works.
So I wrote a code for my job that is basically a quiz. It's HTML code. I wrote it so that it would be a set order for each question. Then I realized it'd be easy to memorize answers. I found a randomizer for links, but I need to know how to get it to remember which questions it's been to do they don't show up in the quiz again. Is this possible?
<html>
<head>
<title>
Easy Mode
</title>
<script src="https://randojs.com/1.0.0.js"></script>
</head>
<body align="center">
Welcome to Easy Mode<br>
In this mode, menu descriptions will be given <br>
after each image to make it easier to identify<br>
When you are ready, click the next button below <br>
Next
<script>
var allQuestions = ["question 1.html", "question 2.html", "question
3.html", "question 4.html"];
function getNextQuestion() {
var questions = JSON.parse(localStorage.getItem("questions"));
if (questions === null) questions = randoSequence(allQuestions);
if (questions.length == 0) return "VICTORY.html";
var question = questions.pop().value;
localStorage.setItem("questions", JSON.stringify(questions));
return question;
}
</script>
</body>
</html>
Thank you for all your help already given and any that will be given in the future

Have a look at this.
Uncomment the lines with localStorage when using (SO does not allow localStorage in snippets)
the script needs to be in each page
I suggest you ajax the question in, instead.
Anyway: working example
const allQuestions = ["question_1.html", "question_2.html", "question_3.html", "question_4.html"];
let storedQuestions;
// storedQuestions = localStorage.getItem("questions");
let questions = storedQuestions ? JSON.parse(storedQuestions) : allQuestions;
function getNextQuestion() {
let href = questions.length === 0 ? "VICTORY.html" : questions.splice(Math.floor(Math.random()*questions.length),1);
// localStorage.setItem("questions", JSON.stringify(questions));
alert(href+"\n"+questions); // remove when happy
return href;
}
Welcome to Easy Mode<br> In this mode, menu descriptions will be given <br> after each image to make it easier to identify<br> When you are ready, click the next button below <br>
Next
NOTE You need to get rid of the localStorage item to be able to run the quiz again. In my victory.html I have a button with
<button type="button" onclick="localStorage.removeItem('questions'); location.replace('start.html')">reset</button>
To reset in the start page have this ONLY in the top of the script on the start page:
localStorage.removeItem('questions')

Related

How to keep user's input printed?

I'm trying to add a comments from user, so I just tried to read the input and send it to print it , but the problem is that the printed input disappears as soon as I refresh the page or enter another input.
so I want to keep all user's appearing always even when refreshing the page or re-entering a new comment.
code :
<div>
<input type="text" name="comments" placeholder = "Your comment goes here .. " class = "sug-box" id = "UserComment">
<button class = "send-box" onclick="go()">Add</button><i class="fa fa-send-o"></i>
<p id = "t"></p>
</div>
<script>
function go(){
var x = document.getElementById("UserComment").value;
document.getElementById("t").innerHTML = x;
}
</script>
There are two ways to do this depending on what your use case is.
The first is to use localstorage, which is significantly easier than using a database but has some downsides. Localstorage could be used if the comments were personal (meaning nobody else sees them). The problem with this is that localstorage is insecure.
Localstorage is a set key/value pairs stored on the users machine until deleted.
This is how you use localstorage:
// Place something in localstorage:
window.localStorage.setItem('key', 'value')
//Get something from localstorage:
window.localStorage.getItem('key')
//Delete item from localstorage
window.localstorage.removeItem('key')
Your full application might look something like this:
Javascript:
document.getElementById('comment').innerHTML = window.localStorage.getItem('comment') || ''
HTML:
<!DOCTYPE html>
<html>
<head>
<title>*title here*</title>
</head>
<body>
<textarea placeholder="Type comment here" id="comment"></textarea>
<br/>
<button onmouseup="window.localStorage.setItem('comment',document.getElementById('comment').value)">Submit</button>
</body>
</html>
The second way to do this is to use a database.
There are many different ways to do this, but I would recommend using node.js + express for middleware and mongodb for your database.
Here are some links to get you started:
node.js
npm
express
mongodb
Let me know if I missed anything and/or misunderstood the question.
I think I have a solution that should work for you. I have renamed and refactored some of your code a little, feel free to change it back to the original version if you wish. For me, this was easier to read. I also put the JS in a separate file, but you could accomplish the same task using the script tag.
Here is a link to a JSFiddle that shows it in action JSFiddle User-Comments-App. The code in the fiddle has been modified to work on that site, don't pay attention to it, look at the example below! You can't do page refreshes on JSFiddle so I simulated it with a Refresh Page button and a little timer function that clears the list then repopulates it from local storage.
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<!-- calls this function on refresh to pull any coments from local storage -->
<body onload="populateUL()">
<div>
<input type="text" name="comments" placeholder = "Your comment goes here .. " class = "sug-box" id = "UserComment">
<button class = "send-box" onclick="parseUserComment()">Add</button><i class="fa fa-send-o"></i>
<p id = "t"></p>
</div>
<div id="comment-container">
<ul>
<!-- <li> items will be inserted here -->
</ul>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
JavaScript
var commentUL = document.getElementById('comment-container').firstElementChild;
var commentNumber = 0;
function parseUserComment() {
var userComment = document.getElementById("UserComment").value;
storeUserComment(userComment, commentNumber);
displayUserComment(userComment);
commentNumber++;
}
function displayUserComment(userComment) {
var li = document.createElement('li');
li.textContent = userComment;
commentUL.appendChild(li);
}
function storeUserComment(userComment, commentNumber) {
window.localStorage.setItem(`comment-${commentNumber}`, userComment);
}
function populateUL() {
if (window.localStorage.length > 0) {
var i;
for (i = 0; i < localStorage.length; i++) {
var userComment = window.localStorage.getItem(`comment-${i}`);
displayUserComment(userComment);
}
// we need to reset the counter to begin in the last element of the array when we refresh the page.
commentNumber = localStorage.length;
}
}
Here's a brief breakdown of what's going on, let me know if you have any questions or if something is unclear.
Code Explanation
When the user clicks the 'Add' button, the parseUserComment() function will run. This function takes care of storing the comment in local storage, and displaying the comment on the screen. You'll notice that we pass the work of displaying the comment and storing the comment on to helper functions storeUserComment() and displayUserComment(). The only thing that parseUserComment() actually does is get the user's comment and increment the counter commentNumber:
var commentNumber = 0;
function parseUserComment() {
var userComment = document.getElementById("UserComment").value;
storeUserComment(userComment, commentNumber);
displayUserComment(userComment);
commentNumber++;
}
So, we have the user's comment, and we pass along the userComment to the helper function storeUserComment, which is just a single function call that add's the comment to local storage, using a naming convention 'comment-{commentNumber}'. This would mean the first comment would be 'comment-0', the second 'comment-1'. We use the 0-based system like in arrays. Note the use of template literals to allow us to easily concatenate the commentNumber to the string:
function storeUserComment(userComment, commentNumber) {
window.localStorage.setItem(`comment-${commentNumber}`, userComment);
}
After we have stored the user comment, we want to display it. And this function will also be used to display the user comments on a page refresh. We simply create a new 'li' element, and then make that elements text content the userComment. We then add this element to the 'ul' that sit's inside the div.comment-container, which we selected at the beginning of the file, using the appendChild() method:
// at beginning of file
var commentUL = document.getElementById('comment-container').firstElementChild;
function displayUserComment(userComment) {
var li = document.createElement('li');
li.textContent = userComment;
commentUL.appendChild(li);
}
So that covers the parseUserComment() function and the helpers it calls. Next we need to see how to show the user's comments when the page refreshes. For this, we add an event listener to the 'body' element for the 'onload' event:
<body onload="populateUL()">
The populateUL() function will check to see if there are any items in local storage, and if so, it will loop through those items and call the displayUserComment() function for each item:
function populateUL() {
if (window.localStorage.length > 0) {
var i;
for (i = 0; i < localStorage.length; i++) {
var userComment = window.localStorage.getItem(`comment-${i}`);
displayUserComment(userComment);
}
// bottom of function left off for clarity
At the end of the function, we have to be sure to set the commentNumber to the length of the localStorage array, which would be the last element. So, if you had two comments in localStorage, you would have 'comment-0' and 'comment-1'. The length of localStorage would be 2. We would print out 'comment-0' and 'comment-1' in the loop, then the 'i' variable would increment to 2, and the loop would stop. At this point, we can assign the length of localStorage to the commentNumber, so that if the user wanted to add a new comment, it would start numbering at 2 ('comment-2'):
commentNumber = localStorage.length;

How to set a textbox to an eval() in javascript

Okay, so I am trying to make a quiz where you enter some code and the quiz executes the code to see if what you typed is the same as the answer.
Here is the code and this is how the webpage looks like:
questions = "PRINT HELLO"
document.getElementById("Question").innerHTML = questions
function check(){
document.getElementById("answertext").innerHTML = eval(document.getElementById("answerbox").value)
}
#answerbox{
width:100%;
height:500px;
font-size:25px;
}
<h1>QUIZZZ</h1>
<h2 id = Question>JAVASCRIPT CONSOLE AND EXERCISES</h1>
<h1 id = "hi"></h1>
<textarea rows="4" cols="50" id = "answerbox">
//put your answer here
</textarea>
<textarea rows= '4' cols = "50" id = "answertext">lol</h1>
</textarea>
<input type = "submit" onclick = "check()">
Run the code to see
I want the user to enter a document.write() statement inside the textbox, and have the evaluated code to be shown in the smaller multiline text box.
Try to put a document.write() statement in the textbox and run it. You should see a new page instead of the answer written in the text box.
I know that document.write is a bad practice to output things in javascript, and I know that you can edit raw HTML, but is there any other way a user can print a message without doing any of these choices?
Don't use eval.
Using eval is considered to be a bad practice. Read more for Why here. You can ask your user to just return the answer using a return statement as shown below, instead of asking them to do something complicated like document.write().
// Ask them to do this:
var codeFromTheAnswerBox = "var answer = 'HELLO'; return answer;"
// instead of this:
// var codeFromTheAnswerBox = "var answer = 'HELLO'; document.write(answer)";
// execute user's code
var code = new Function(codeFromTheAnswerBox);
var returnValue = code();
// Now do whatever you want to do with the answer like the following
alert("Your answer is " + returnValue);
You can use .append instead of document.write()
document.body.append("Hello World!", document.createElement('p'));
If you go to the Console tab of the DevTools in your browser, you can type javascript code and press enter to execute it. You will get helpful error messages that should help you with your project.
Ok. I realized your problem.
You can use iframe for this purpose. Add an iframe with an id similar 'answerIframe' instead of #answertext element.
Then move your #answertext element to a separated html and set address of iframe to it.
In iframe:
window.check=function(){
document.getElementById("answertext").innerHTML =
eval(document.answer);
}
And add a button to your iframe too. for iframe's button set this:
onclick="window.check()"
Add an Id to iframe's button similar: iframe_bt.
Now, when user clicks on button (in current page, no iframe) must call this (new check function in your main page):
function check(){
document.getElementById('#answerIframe').contentWindow.document.answer=document.getElementById("answerbox").value;
document.getElementById('#answerIframe').contentWindow.document.getElementById('#iframe_bt').click();
}
Also in your iframe, call a function in document's onload and add answertext dynamically if is not exists (because document.write) or reset the iframe before execute per answer.
Another way is replacing the document.write with other code similar: elem.insertAdjacentHtml(..) or etc before execute it.
Excuse me for any mistake, i typed with my cellphone.
I did not have a tool to test it, but the method and its generalities are correct.

Removing everything after first word JS

The title is a little bland but my problem is explained below.
At the moment I currently have a live search:
This does what I want it to do, but of course, that's only possible with a little bit of JS.
Now when you click one of the options it gives you from your search it'd usually take you to a link, but I added the below JS so that it removes all HTML code from it and it appends the selected username from the drop down into a text box.
<script type="text/javascript">
$(document).ready(function(){
$("#livesearch").click(function(){
var value = $(this).html();
var input = $('#append_value');
var content = value;
var text = $(content).text(); //removes all HTML
input.val(text);
});
});
</script>
Now, this is all perfect and everything but there's a problem. When you select one option from the drop down it appends both options to the text box:
Now, this may have something to do with the code above, but I just want whichever option the user has selected to be appended to the text box.
So, for example, I search for the battlefield and I get a result of battlefield1 and battlefield2. If the user selected battlefield2 I want battlefield2 to be placed in the textbox, and vice versa.
I've been trying to do this since 1pm EST so you can trust me when I say I've looked plenty of times for a solution.
Thank you in advance for your help. :)
Edit:
What I'm doing the search with (yes I realize SQL is deprecated):
index.html
<script type="text/javascript">
function lightbg_clr() {
$('#qu').val("");
$('#textbox-clr').text("");
$('#search-layer').css({"width":"auto","height":"auto"});
$('#livesearch').css({"display":"none"});
$("#qu").focus();
};
function fx(str) {
var s1=document.getElementById("qu").value;
var xmlhttps;
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
document.getElementById("livesearch").style.display="block";
$('#textbox-clr').text("");
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttps=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttps=new ActiveXObject("Microsoft.XMLHTTPS");
}
xmlhttps.onreadystatechange=function() {
if (xmlhttps.readyState==4 && xmlhttps.status==200) {
document.getElementById("livesearch").innerHTML=xmlhttps.responseText;
document.getElementById("livesearch").style.display="block";
$('#textbox-clr').text("X");
}
}
xmlhttps.open("GET","scripts/search_friends.php?n="+s1,true);
xmlhttps.send();
}
</script>
<input type="text" onKeyUp="fx(this.value)" autocomplete="off" name="qu" id="qu" class="form-control" placeholder="Name of the person or group">
<div class="list-group" id="livesearch"></div>
<input type="text" id="append_valueq">
<script type="text/javascript">
$(document).ready(function(){
$("#livesearch").click(function(){
var value = $(this).val();
var input = $('#append_valueq');
var content = value;
var text = $(content).text();
input.val(text);
});
});
</script>
search_friends.php
<?php
include('../Connections/ls.php'); //script to connect to DB
$s1=$_REQUEST["n"];
$select_query="SELECT * FROM users WHERE Username LIKE '%".$s1."%'";
$sql=mysql_query($select_query) or die (mysql_error());
$s="";
while($row=mysql_fetch_array($sql))
{
$s=$s."
<a href='javascript:void(0)'>".$row['Username']."</a>
" ;
}
echo $s;
?>
This ultimately gives me the result you see in the first image.
I'm realizing now that the problem I'm having is the fact that div has an id of livesearch (<div class="list-group" id="livesearch"></div>), so it's selecting the whole div instead of the actual options in the dropdown...
Try using .val() instead of html() while fetching the value.
There is actually a really simple way to do this.
Since you haven't provided your HTML code, I'll show what I would have done.
You can get the value of the click with:
document.getElementById("dropdown").value();
Make sure you don't include the hashtag/pound sign in the id.
Then, you can apply this value, let's say you call it val, this way:
document.getElementById("textbox").value = val
I've created a JSFiddle that kind-of shows the concept. See if you can get it to work with your own code: https://jsfiddle.net/1j4m1ekc/7/
If the problem persists, just let me know. I'd also like to see your html.
I don't need a solution right away for this as I've found another alternative to do what I want to do, but it would be greatly appreciated in case someone else from the Stackoverflow community has a question similar to this and need a solution. The solution I found is below.
This is still considered a live search but, I created a scrollable container and listed all of the users in that container, so it now looks like this.
Now from that container I found a script online that will filter out any and all users that do not match the input from the search box. The script I found is from here: Live Search and if you want to take a look at a demo as to how the script works, View Demo. So now when I enter a search term into the text box it looks like this
This may not be the greatest solution but it works for me and does what I want it to do. Maybe it'll work for you as well :)

Why am I not getting a value from my getElementById()?

I want to take in a value from the URL, add it to a span tag on my slots.html so the user can read it, then pull that same value into another JS file to alter it as the game progresses. The Url code works fine and I get the appropriate value:
elId("wallet").textContent = (values["bank"]); which returns for example 1234.
<p>Player Bank: <span id="wallet"></span></p> which displays 1234 properly
but when I try to get the value from my html (var elWallet=elId("wallet");)to another JS page it returns <span id="wallet"></span> instead of 1234.
Could someone please explain to me what I am doing wrong, and how to improve my understanding of this. Any help would be appreciated!
EDIT: var elId = function(id) {return document.getElementById(id); } is the function I wrote to make writing document.get easier.
EDIT 2: Well I found the issue, talking through with a friend, thanks anyways for all the help.
Could please try using innerHTML to get the values.
elWallet.innerHTML will return the value inside your span tag.
Update:
This works for me. may be you might have put wallet element after the script tag.
Player Bank: 1234
<script>
var elId = function(id) {return document.getElementById(id); }
var elWallet=elId("wallet");
console.log(elWallet.textContent);
console.log(elWallet.innerHTML);
</script>
</body>
</html>

How do I check for specific content in a p class and create an if statement based on that with javascript in an html file?

I'm trying to make a text box on my web page in which the content changes when you click around on the page, and to make it so that I can easily change the content of the text I'd like to use variables so I only have to change the content of the string variables instead of digging around in the html.
So far I've managed to create the text box and make it possible to change from the first message to the second, but I haven't been able to figure out how to make an if statement to check for the presence of the second message and to display the third.
At the moment my code looks like this (with some stuff taken out, if you want to look at the full code the project is up on GitHub here).
Head:
<head>
<script>
var text1 = "This is Emilia's portfolio site, where you can find her games, illustrations and interaction design projects, as well as a short bio and her contact info.";
var text2 = "What would you like to do?";
//set the first message the mascot character will say
window.onload = function starting () {document.getElementById("changetext").innerHTML = "안녕하세요! Emilia is in Korea right now, but if you need help I\'m here to guide you!";
}
//set what will happen once you click the textbox
function characterDialogue(){
//if (#changetext == "안녕하세요! Emilia is in Korea right now, but if you need help I\'m here to guide you!"){
document.getElementById('changetext').innerHTML = text1 ;
//}
}
</script>
</head>
Body:
<body onclick="characterDialogue()">
<div class="textbox">
<div class="textboxspeechtext">
<p id="changetext"></p>
</div>
</div>
</body>
Currently, the if statment present doesn't work at all. I haven't really done any work with javascript before so I'm having trouble understanding how you link it together with html, and any similar problems that had been solved didn't seem to be directly applicable to what I want to do. Thank you for reading.
You need to get the innerHtml back and compare against the variables:-
var text1 = "안녕하세요! Emilia is in Korea right now, but if you need help I\'m here to guide you!";
var text2 = "This is Emilia's portfolio site, where you can find her games, illustrations and interaction design projects, as well as a short bio and her contact info.";
var text3 = "What would you like to do?";
//set the first message the mascot character will say
window.onload = function starting() {
document.getElementById("changetext").innerHTML = text1;
}
//set what will happen once you click the textbox
function characterDialogue() {
var current = document.getElementById('changetext').innerHTML;
if (current == text1){
document.getElementById('changetext').innerHTML = text2;
}
if (current == text2){
document.getElementById('changetext').innerHTML = text3;
}
}
<body onclick="characterDialogue()">
<div class="textbox">
<div class="textboxspeechtext">
<p id="changetext"></p>
</div>
</div>
</body>
Your IF statement compares "#changetext" with the first text, this is incorrect. Instead you need to get the current content of changetext and compare it against text1.
Get the HTML content using:
document.getElementById('changetext').innerHTML
Set the HTML content using: document.getElementById('changetext').innerHTML = "New Text"
So your IF statement should look like:
if (document.getElementById('changetext').innerHTML == text1)

Categories

Resources