Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a slot machine that I made recently, but I would like to make it look a bit better.
https://codesandbox.io/s/slot-machine-xip7x?file=/index.html:0-1480 (I apologize, I was having issues copy and pasting the code into a code sample :( I am new to this site.)
Here is the result of that code: https://xip7x.csb.app/
Every time you roll, a bullet point show up at the left side of your screen with the result in the middle. When you roll multiple times, the new results are just added to what is already there. Can anybody make it so that there are no bullet points, and every time you roll it replaces your previous roll and only shows the new one, so you only have one roll on the page at all times. I am new to coding and would love to complete this project. If anybody could help me out and explain what they did, I would love that. Thanks!
is this what u want?
var firstx = ["X", "O", "L", "L"];
var secondx = ["X", "O", "L", "L"];
var thirdx = ["X", "O", "L", "L"];
function randIndex() {
var randIndex1 = Math.floor(Math.random() * 4);
var randIndex2 = Math.floor(Math.random() * 4);
var randIndex3 = Math.floor(Math.random() * 4);
var first = firstx[randIndex1];
var second = secondx[randIndex2];
var third = thirdx[randIndex3];
var btn = document.getElementById("btn");
var sent = document.getElementById("sent");
var result = first + " " + second + " " + third;
if (result == "X X X") {
alert("CONGRATULATIONS! YOU WIN!");
}
sent.innerHTML ="<li>" + result + "</li>";
btn.innerText = "Roll Again";
}
font-family: helvetica;
text-align: center;
-webkit-text-fill-color: black;
}
body {
background-color: lightcoral;
}
<!DOCTYPE html>
<html>
<head>
<title>Slot Machine</title>
<meta charset="UTF-8" />
</head>
<body>
<h1>Slot Machine</h1>
<p>
Welcome to the slot machine! To play, click the "Roll" button. If you get
three X's, YOU WIN! Have fun and Enjoy your new gambling addiction!
</p>
<br />
<button id="btn" onclick="randIndex();">
Roll
</button>
<ul id="sent"></ul>
<br /><br />
<hr />
<br /><br />
</body>
</html>
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Goal:
Write a JavaScript that reads several lines of text and print a table indicating number of one-letter words, two-letter words, etc.appearing in the text.
This is my code to reads several lines of text and prints a table indicating the number of one-letter words, two-letter words, three-letter words, etc. appearing in the text. For example, the phrase; Whether 'tis nobler in the mind to suffer.
The output will be:
Word length Occurrences
1 0
2 2
3 1
4 2 (including 'tis)
5 0
6 2
7 1
But I do not get any output..So I need help. This is what I currently have:
<!DOCTYPE html>
<html>
<head>
<title>
Assignment 1
</title>
<meta charset = "utf-8">
<b>Assignment1 <br> <br>
Name: Omnia Hassan Elshaer <br> <br>
Current Date: <b>
</head>
<body>
<script type="text/javascript">
// the current date.
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
// function to calculate number of occurrences.
function search()
{
var str = document.getElementById("string").value;
var c = new Array();
c=str.split(" ");
var count = new Array(15);
for(var i=0;i<count.length;i++){
count[i]=0;
}
var wordlenght;
for(var j=0;j<c.length;j++){
wordlenght=c[i].length;
count[wordlenght]++;
}
var content= "<table>"+"<thead><th>Word length</th><th>Occurrences</th></thead><tbody>";
for(var m=0;m<count.length;m++){
content+="<tr><td>"+m+"</td><td>"+count[m]+"</td></tr>";
}
content+="</tbody></table>";
document.getElementById("result").innerHTML = content;
//output(count);
}
/*function output(count){
var content= "<table>"+"<thead><th>Word length</th><th>Occurrences</th></thead><tbody>";
for(var m=0;m<count.length;m++){
content+="<tr><td>"+m+"</td><td>"+count[m]+"</td></tr>";
}
content+="</tbody></table>";
document.getElementById("result").innerHTML = content;
}*/
</script>
<br> <br>
<label><b> Enter the string to determine the number of occurrences :<b>
<input name = "string" type = "text" /> </label> <br> <br>
<input type = "button" value = "Result" text="Result" onclick ="search()"/> <br> <br>
<div id="result"> </div>
</body>
</html>
Try this:
const sentence = "Whether 'tis nobler in the mind to suffer"
// get an array with the length of each word
lengths = sentence.split(" ")
.map(word => word.length)
// get the longest word, e.g. "7"
const max = Math.max(...lengths)
// make a sequence from 0 to the longest word: 0,1,...,7
counts = [...Array(max).keys()].map(n => {
// check how often the number occurs in the 'lengths' array
return lengths.filter(x => x === n + 1).length
})
document.getElementById('results').innerHTML = counts.map((count, i) => {
return `<tr><td>${i+1}</td><td>${count}</td></tr>`
}).join('')
<table id="results"></table>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to make this script auto change between the four after 30 seconds, I am not to good at jquery but I wanted to give it a try. This is all on a .php page I am using to bring up the javascript from my other folders.
<div id="subnavi">
<div id="subnavi-user">
<div style="margin-top:7px"><b>Fact:</b> <script language="JavaScript">
var r_text = new Array ();
r_text[0] = "{hotelName} was founded in 2011 by Kyle";
r_text[1] = "{hotelName} strives to remain as professional as possible.";
r_text[2] = "{hotelName} will only keep on growing if you vote daily!";
r_text[3] = "Purchasing VIP in the forums helps with the monthly server costs.";
r_text[4] = "{hotelName} Is a new and developing RP!";
window.setInterval(function(){
var i = Math.floor(4 * Math.random())
document.write(r_text[i]);
var random = r_text[1];
}, 5000);
</script>
</div>
</div>
<div id="subnavi-search">
<div id="subnavi-search-upper">
<ul id="subnavi-search-links">
<li>Sign Out</li>
I am not sure if this is what you are looking for but here it is:
This script will run every time you reload the page. IF you need it to work in a different way just update your question and i will update my script.
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var r_text = new Array();
r_text[0] = "Hello";
r_text[1] = "Test";
r_text[2] = "We are the lions";
r_text[3] = "Fight";
r_text[4] = "Switch!";
window.setInterval(function(){
var i = Math.floor(5 * Math.random())
var random = r_text[i];
$('#r_text').html(random);
}, 5000); // you can change the interval here
The HTML part
<div id="r_text"></div>
Check this out here
Update
Change your Math.floor to count to 5 because your array has 5 elements in it not 4
Update 2 Your file should look like something like this
<!Document html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var r_text = new Array();
r_text[0] = "Hello";
r_text[1] = "Test";
r_text[2] = "We are the lions";
r_text[3] = "Fight";
r_text[4] = "Switch!";
window.setInterval(function(){
var i = Math.floor(5 * Math.random())
var random = r_text[i];
$('#r_text').html(random);
}, 5000); // you can change the interval here
</script>
</head>
<body>
//Add your html/php code here and pick a place where to show the response of your function. Something like <div id="r_text"></div>
</body>
</html>
So I'm trying to make my index.html be a page that asks the user a question before allowing him/her to access home.html. (The fact that the user could simply open up site_name.com/home is something I'll deal with later lol. Bear with me for now).
Here's my game plan:
When the user opens the page, a random arithmetic question will be pasted into a div. The arithmetic question will be 2 single-digit positive integers and one of the binary operations +, - or *. The answer somehow needs to be stored as a global variable (This is one of the things I'm stuck on). I've constructed the following function for that purpose.
var randquest = function ()
{
var ops = ["+", "-", "*"];
var num1 = Math.floor(Math.rand() * 10);
var num2 = Math.floor(Math.rand() * 10);
var thisOp = ops[Math.floor(Math.rand() * 10) % 3];
var myDiv = document.getElementById("questiondiv");
var myNewNode = document.createElement('div class="outerdiv" id="questiondiv"')
var myContent = document.createTextNode("<p><b>Question:</b> " + num1 + " " + thisOp + " " + num2 + "</p>");
var myNewNode.appendChild(myContent);
var myDiv.appendChild(myNewNode);
answer = new String();
switch (thisOp)
{
case "+"
{
answer = (num1 + num2).toString();
}
case "-"
{
answer = (num1 - num2).toString();
}
case "*"
{
answer = (num1 * num2).toString();
}
}
}
Then, I need a function to check that what a user inputs into the input text cell with id ans is the correct answer to the question that was generated.
var checker = function()
{
var ipt = document.getElementById("ans").value;
if (ipt != answer)
{
alert("Wrong answer. Entrance not granted.");
return;
}
else
{
// Open up home.html
}
}
But for that to work, I somehow need answer to have been a global variable, and I somehow need a procedure inside the else statement that opens up home.html. How do I do this? I'm at a roadblock.
Here's the whole page thus far, if you care to see it:
<html>
<head>
<title>
Sentinel page
</title>
<style type="text/css">
body
{
}
.innerdiv
{
z-index: -1;
position: absolute;
top: 0px;
left: 0px;
width: 700px;
}
.outerdiv
{
width: 700px;
border: 2px solid #FFF;
padding: 10px;
margin: 5px;
text-color: blue;
}
.outerdiv:nth-of-type(2n+0)
{
background: grey;
}
.outerdiv:nth-of-type(2n+1)
{
background: #FFFFCC;
}
#headerdiv
{
text-align: center;
}
#maindiv
{
}
#footerdiv
{
}
p
{
color: blue;
}
h1
{
color: red;
text-shadow: 2px 2px white;
}
</style>
<script>
var randquest = function ()
{
var ops = ["+", "-", "*"];
var num1 = Math.floor(Math.rand() * 10);
var num2 = Math.floor(Math.rand() * 10);
var thisOp = ops[Math.floor(Math.rand() * 10) % 3];
var myDiv = document.getElementById("questiondiv");
var myNewNode = document.createElement('div class="outerdiv" id="questiondiv"')
var myContent = document.createTextNode("<p><b>Question:</b> " + num1 + " " + thisOp + " " + num2 + "</p>");
var myNewNode.appendChild(myContent);
var myDiv.appendChild(myNewNode);
answer = new String();
switch (thisOp)
{
case "+"
{
answer = (num1 + num2).toString();
}
case "-"
{
answer = (num1 - num2).toString();
}
case "*"
{
answer = (num1 * num2).toString();
}
}
}
var checker = function()
{
var ipt = document.getElementById("ans").value;
if (ipt != answer)
{
alert("Wrong answer. Entrance not granted.");
return;
}
else
{
// Open up home.html
}
}
</script>
</head>
<body>
<div class="innerdiv">
</div>
<div class="outerdiv" id="headerdiv">
<h1>my_site</h1>
</div>
<div class="outerdiv" id="introdiv">
<p>Welcome to my site. Before you can enter the main page, I need to make sure you're human. So please answer the question below.</p>
</div>
<div class="outerdiv" id="questiondiv">
<!-- Div to house the arithmetic quesiton -->
</div>
<div class="outerdiv" id="answerdiv">
<p><b>Answer:</b></p> <input type="text" id="ans"> <input type="button" value="Submit" onclick="checker">
</div>
<div class="outerdiv" id="footerdiv">
<p>Last modified: 03/31/2014</p>
</div>
</body>
</html>
If you use JavaScript, you risk people being able to use developer tools to find the answer to use an automated system to get in. Just because a user can't see the answer doesn't mean it's not in the HTML code. The browser has access to this answer, and a bot attempting to get into the site will also have access to it. If you hit the F12 key in Internet Explorer, you'll get developer tools, including a DOM explorer, which will give you access to the entire page in raw HTML code.
You should use something like PHP for this situation. PHP is much easier for printing elements and text than JavaScript, and it's server-side, so code is executed on the web server. Here's how you should set it up.
When the user goes to the website for the first time, the server will redirect to the page captcha.php. Pages other than index.php (the home page, I'm assuming) should also redirect to captcha.php if they haven't answered the question. This pagehas the random math problem generated by PHP, and the <form> uses two POST variables: the answer to the problem, and a unique CAPTCHA code for each question, which is in the <form> already through an <input type="hidden"> tag. PHP can put this unique CAPTCHA session code into the value attribute without JavaScript. When the question is answered, the browser should go to a page to check the answer (ex. captcha_check.php).
Example captcha.php page:
<p>Math problem generated by PHP</p>
<form action="captcha_check.php" method="post">
<input type="hidden" name="captcha-id" value="CAPTCHA code generated by PHP" />
<input type="text" name="captcha-solution" />
<input type="submit" value="Continue" />
</form>
The captcha_check.php page should use the CAPTCHA session code and solution sent to it by POST to check, and redirect to the captcha.php page is the answer is wrong, or redirect to the index.php page otherwise. Before redirecting to the index.php page if the answer is correct, the captcha_check.php page should store a cookie for the session. This way, the cookie is sent to all pages in the HTTP headers, so every page can verify the session. The cookie can remain on the computer forever if you'd like, letting the user visit multiple sessions without the burden.
In general, math problems for CAPTCHAs are not secure, but they're much easier than the standard RECAPTCHAs by Google. If you're looking for a secure CAPTCHA that isn't completely irritating, take a look at PlayThru by areyouahuman.com. http://areyouahuman.com/site-owners/playthru/
Just declare your variable ipt globally, i.e., outside of the function definition.
var ipt;
var checker = function() {
// set ipt value here.
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble making the questions random. If you could help, it would be awesome!
(If you have spear time; I've been given the task to mark correct answer with a green feather and wrong answers with red feather, for instance, if you get 3 correct and 2 wrong. It will show 3 green feathers and 2 red feathers as score.) Thank you!
<script type="text/javascript">
var questions = [
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'],
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'] // Note: no comma after last entry
];
var qNo = 0;
var correct = 0;
var cnt = 0;
function NextQuestion(response) {
if ((qNo < questions.length) && (response == questions[qNo][1])) {
correct++;
}
document.getElementById('score').innerHTML = 'Correct ' + correct + ' of 6 questions';
qNo++;
if (qNo < questions.length) {
document.getElementById('Pic').src = questions[qNo][0];
cnt++;
}else{
alert('Quiz is done. You got ' + correct + ' points!');
}
}
onload = function() {
document.getElementById('Pic').src = questions[0][0];
}
</script>
</head>
<body>
<div align="center">
<h1>Which car is it?</h1>
<img src="" id="Pic" height="200" width="250">
<p>Is it
<button onclick="NextQuestion('0')">Red</button>
<button onclick="NextQuestion('1')">Black</button>
<button onclick="NextQuestion('2')">Yellow</button>
<p>Your score: <br>
<span id="score"></span>
</div>
</body>
</html>
Well, your questions are in an array. So what you should be researching is how to randomise the order of an array.
questions.sort(function() { return Math.floor(Math.random() * 2); });
<!DOCTYPE HTML>
<html>
<head>
<title>Zautra Levels</title>
<h2 style="font-family: Trebuchet MS; color: blue;"">Zautra Levels</h2>
<p> </p>
</head>
<body>
<p>Clickables:</p>
<button id="swag" onclick="lmao()">Gain XP</button> <button id="gold" onclick="getgold()">Get Gold</button> <button id="buyupgrade" onclick="buyupp()">Level Up!</button>
<p> </p>
<div id="total">XP: 0</div>
<div id="goldt">Gold: 0</div>
<div id="upgradess">Level: 0</div>
<div id="upcostt">Required XP: 25</div>
<script>
var clicks = 0; // How many clicks you have
var upgrades = 0; // How many upgrades you have purchased
var upcost = 25; // How much the upgrades cost
var gold = 0; // How much gold you have
function updateclicks() { // Declares the function that updates the "Zautra Clicks" Text.
var v=document.getElementById("total");
v.innerHTML = 'XP: ' + clicks;
}
function updategold() { // Declares the function that updates the "Zautra Clicks" Text.
var g=document.getElementById("goldt");
g.innerHTML = 'Gold: ' + gold;
}
function updateupgradecounter() { // Declares the function that updates the "Upgrades:" Text.
var y=document.getElementById("upgradess");
y.innerHTML = 'Level: ' + upgrades;
}
function updateupcost() { // Declares the function that updates the "Upgrade Cost:" Text.
var z=document.getElementById("upcostt");
z.innerHTML = 'Required XP:' + upcost;
}
var x=document.getElementById("swag"); function lmao() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
clicks+=1;
updateclicks();
}
var j=document.getElementById("gold"); function getgold() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
gold+=1;
updategold();
}
var c=document.getElementById("buyupgrade"); function buyupp() {
if (clicks >= upcost) {
clicks-=upcost
upgrades+=1
upcost*=2
updateclicks();
updateupgradecounter();
updateupcost();
}
else
{
var clicksdif = upcost - clicks;
confirm("You need " + clicksdif + " more XP to level up.");
}
}
</script>
</body>
</html>
This is the code for my game that I am working on.
I'm trying to add a button, and when you press it, it saves all of the variables.
If you're level 5 with 26 XP, and 7 gold, you refresh the page, you still have those stats instead of losing them on refresh.
Please help!
(And yeah, I do realize that the code is really messed up, but that is a small issue. I'll fix that sooner or later.)
I believe that actually the easiest way, easier than cookies, is to pass the values via the URL. Example:
<form action="yourPage.php?gold=$amount&level=$whatlevel&experience=$experience" method="POST">
//Your refresh button here
</form>
and then to retrieve those variables when the page reloads, use: gold=$_POST['gold']
Another option as well is to use the GET method instead of POST.
Keep in mind that the file extension needs to be php for this code to work.
you could create a cookie in php:
setcookie("NameOfTheCookie",$value,$expireTime)
and $value can be an array of values as well.