for my college project im trying to limit the amount of times one of my buttons is being clicked to 3 times, I've been looking everywhere for code to do it and found some yesterday, it does give me alert when I've it the max amount of clicks but the function continues and im not sure why, here is the code I've been using.
var total = 0
var hitnumber = 0
var username = prompt("Enter username", "Player 1")
var compscore = 18
var card_1 = 0
var card_2 = 0
var ClickCount = 0
function NumberGen() {
hitnumber = Math.floor((Math.random() * 2) + 1);
document.getElementById("Random Number").innerHTML = username + " has
drawn " + hitnumber;
}
function Total_Number() {
total = total + hitnumber + card_1 + card_2;
document.getElementById("Total").innerHTML = username + " has a total
of " + total;
if(total >21){
window.location="../End_Game/End_Lose_Bust.html";
}
}
function Random_Number() {
card_1 = Math.floor((Math.random() * 2) + 1);
card_2 = Math.floor((Math.random() * 2) + 1);
document.getElementById("Stcards").innerHTML = username + " has drawn "
+ card_1 + " and " + card_2 + " as their first cards.";
}
function menuButton(button) {
switch(button)
{
case "Stick":
if (total > 21) {
window.location="../End_Game/End_Lose_Bust.html";
} else if (total == 21){
window.location="../End_Game/End_Win_21.html";
} else if (total > compscore) {
window.location="../End_Game/End_Win.html";
} else if (total == compscore) {
window.location="../End_Game/End_Draw.html";
} else {
window.location="../End_Game/End_lose.html";
}
}
}
function Hidebutton() {
document.getElementById("Hit").style.visibility = 'visible';
document.getElementById("Stick").style.visibility = 'visible';
document.getElementById("Deal").style.visibility = 'hidden';
}
function countClicks() {
var clickLimit = 3;
if(ClickCount>=clickLimit) {
alert("You have drawn the max amount of crads");
return false;
}
else
{
ClickCount++;
return true;
}
}
HTML
<!doctype html>
<html>
<head>
<title>Pontoon Game</title>
<link rel="stylesheet" type="text/css" href="Main_Game.css">
</head>
<body>
<h1>Pontoon</h1>
<div id="Control">
<input type="button" id="Hit" onclick="NumberGen(); Total_Number(); countClicks()" value="Hit" style="visibility: hidden" />
<input type="button" id="Stick" onclick="menuButton(value)" style="visibility: hidden" value="Stick" />
<input type="button" id="Deal" onclick="Hidebutton(); Random_Number()" value="Deal" />
</div>
<div class="RNG">
<p id="Stcards"></p>
<p id="Random Number"></p>
<p id="Total"></p>
</div>
<div class="Rules">
<p>
Welcome to Pontoon, the goal of the game is to make your cards reach a combined value of 21 before the dealer (computer). during the game you will have two clickable buttons, these are hit and stick.
</p>
<p>
>Hit - This button allows you to collect another card.
</p>
<p>
>Stick - This buttom allows you to stay at the value of cards you have, you should only use this button at the end of the game when you feel you cannot get any closer to 21 without going bust.
</p>
<p>
Going bust means you have gone over 21, when this happens the game will automaticly end as you have gone bust.
</p>
</div>
</body>
</html>
Cheers in advance.
You are calling countClicks at the end of onclick. Change it to this:
if (countClicks()) { NumberGen(); Total_Number();}
Try this
var count = 0;
function myfns(){
count++;
console.log(count);
if (count>3){
document.getElementById("btn").disabled = true;
alert("You can only click this button 3 times !!!");
}
}
<button id="btn" onclick="myfns()">Click Me</button>
I have edited your code also following is your code
var total = 0
var hitnumber = 0
var username = prompt("Enter username", "Player 1")
var compscore = 18
var card_1 = 0
var card_2 = 0
var ClickCount = 0
function NumberGen() {
hitnumber = Math.floor((Math.random() * 2) + 1);
document.getElementById("Random Number").innerHTML = username + " has drawn " + hitnumber;
}
function Total_Number() {
total = total + hitnumber + card_1 + card_2;
document.getElementById("Total").innerHTML = username + " has a total of " + total;
if (total > 21) {
window.location = "../End_Game/End_Lose_Bust.html";
}
}
function Random_Number() {
card_1 = Math.floor((Math.random() * 2) + 1);
card_2 = Math.floor((Math.random() * 2) + 1);
document.getElementById("Stcards").innerHTML = username + " has drawn " +
card_1 + " and " + card_2 + " as their first cards.";
}
function menuButton(button) {
switch (button)
{
case "Stick":
if (total > 21) {
window.location = "../End_Game/End_Lose_Bust.html";
} else if (total == 21) {
window.location = "../End_Game/End_Win_21.html";
} else if (total > compscore) {
window.location = "../End_Game/End_Win.html";
} else if (total == compscore) {
window.location = "../End_Game/End_Draw.html";
} else {
window.location = "../End_Game/End_lose.html";
}
}
}
function Hidebutton() {
document.getElementById("Hit").style.visibility = 'visible';
document.getElementById("Stick").style.visibility = 'visible';
document.getElementById("Deal").style.visibility = 'hidden';
}
function countClicks() {
var clickLimit = 3;
if (ClickCount >= clickLimit) {
alert("You have drawn the max amount of crads");
return false;
} else {
NumberGen();
Total_Number();
ClickCount++;
return true;
}
}
<html>
<head>
<title>Pontoon Game</title>
<link rel="stylesheet" type="text/css" href="Main_Game.css">
</head>
<body>
<h1>Pontoon</h1>
<div id="Control">
<input type="button" id="Hit" onclick=" countClicks()" value="Hit" style="visibility: hidden" />
<input type="button" id="Stick" onclick="menuButton(value)" style="visibility: hidden" value="Stick" />
<input type="button" id="Deal" onclick="Hidebutton(); Random_Number()" value="Deal" />
</div>
<div class="RNG">
<p id="Stcards"></p>
<p id="Random Number"></p>
<p id="Total"></p>
</div>
<div class="Rules">
<p>
Welcome to Pontoon, the goal of the game is to make your cards reach a combined value of 21 before the dealer (computer). during the game you will have two clickable buttons, these are hit and stick.
</p>
<p>
>Hit - This button allows you to collect another card.
</p>
<p>
>Stick - This buttom allows you to stay at the value of cards you have, you should only use this button at the end of the game when you feel you cannot get any closer to 21 without going bust.
</p>
<p>
Going bust means you have gone over 21, when this happens the game will automaticly end as you have gone bust.
</p>
</div>
</body>
</html>
Related
For my collage assignment i need to create a html webpage where if you press the button yes it displays a number and a corresponding image. i have figured out how to create the random number but cannot get the corresponding image to show up when the button in pressed. i am very new to this and any help would be appreciated
This is the java script
function randomNumber() {
var ranNumgen = Math.floor((Math.random() * 6) + 1);
}
console.log("randomNumber");
if ("number" == 1) {
document.getElementById('img1').src = "image/dice1.jpg";
} else if ("number" == 2) {
document.getElementById('img1').src = "image/dice2.jpg";
} else if ("number" == 3) {
document.getElementById("img1").src = "image/dice3.jpg"
} else if ("number" == 4) {
document.getElementById("img1").src = "image/dice4.jpg";
} else if ("number" == 5) {
document.getElementById("img1").src = "image/dice5.jpg";
} else if ("number" == 6) {
document.getElementById("img1").src = "image/dice6.jpg";
}
<head>
<title></title>
<button id="b" onclick="ranNumgen()"> Yes </button>
<button onclick="Num2button()">No</button>
</head>
<body>
<p id="number"> </p>
And this is all my code
<!DOCTYPE html>
<html>
<head>
<title></title>
<button id="b" onclick="ranNumgen()"> Yes </button>
<button onclick="Num2button()">No</button>
</head>
<body>
<p id="number"> </p>
<script type="text/javascript">
function randomNumber() {
var ranNumgen = Math.floor((Math.random() *6) +1);
}
console.log("randomNumber");
if ("number" ==1 ) {
document.getElementById('img1').src ="image/dice1.jpg";
}
else if ("number" ==2) {
document.getElementById('img1').src ="image/dice2.jpg";
}
else if ("number"==3) {
document.getElementById("img1").src="image/dice3.jpg"
}
else if ("number"==4) {
document.getElementById("img1").src="image/dice4.jpg";
}
else if ("number"==5) {
document.getElementById("img1").src="image/dice5.jpg";
}
else if ("number"==6) {
document.getElementById("img1").src="image/dice6.jpg";
}
function Num2button() {
var button2 = "Are you sure"
alert(button2);
}
</script>
</body>
</html>
You can put your logic to assign the picture in your randomNumber function, the best would be to rename it to something like generateRandomPicture.
Then you need an element with the id you have specified and
also I would recommend that you use an eventListener instead of doing the inline scripting.
You can add .addEventListener() to your element.
document.getElementById('b').addEventListener('click', randomNumber);
document.getElementById('b').addEventListener('click', randomNumber);
function randomNumber() {
let number = Math.floor((Math.random() * 6) + 1);
if (number == 1) {
document.getElementById('img1').src = "image/dice1.jpg";
} else if (number == 2) {
document.getElementById('img1').src = "image/dice2.jpg";
} else if (number == 3) {
document.getElementById("img1").src = "image/dice3.jpg"
} else if (number == 4) {
document.getElementById("img1").src = "image/dice4.jpg";
} else if (number == 5) {
document.getElementById("img1").src = "image/dice5.jpg";
} else if (number == 6) {
document.getElementById("img1").src = "image/dice6.jpg";
}
}
<head>
<title></title>
</head>
<body>
<p id="number"> </p>
<img id="img1"></img>
<button id="b"> Yes </button>
<button onclick="Num2button()">No</button>
</body>
I'm aware that the question is already answered and that you are new to this but this is a more scalable approach and looks a bit cleaner.
NOTE: This snippet assumes the images in the array in the correct order, from 1 to N.
let images = [
'https://via.placeholder.com/10',
'https://via.placeholder.com/20',
'https://via.placeholder.com/30',
'https://via.placeholder.com/40',
'https://via.placeholder.com/50',
]
function setRandomImage() {
let index = Math.floor(Math.random() * images.length);
document.getElementById('img').src = images[index];
document.getElementById('num').innerHTML = index + 1;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
As per epascarello's comment, this does not rely on the order of the images but they do have to be in the array.
var images = [
'https://via.placeholder.com',
'https://via.placeholder.com',
'https://via.placeholder.com',
'https://via.placeholder.com',
'https://via.placeholder.com',
]
function setRandomImage() {
let index = Math.floor(Math.random() * images.length) + 1;
document.getElementById('img').src = images[index - 1] + '/' + index + '0';
document.getElementById('num').innerHTML = index;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
And if you always have a static number of images which are properly named you can even do away with the images array.
function setRandomImage() {
let rand = Math.floor(Math.random() * 6) + 1;
document.getElementById('img').src = 'https://via.placeholder.com/' + rand + '0';
document.getElementById('num').innerHTML = rand;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
I'm having trouble with my JS form. So I'm creating a change calculator which takes in two input values - the price and cash. When I explicity put in the actual values inside JS code (like the ones I commented out after confirmValues()), it works just fine. But when I put it in the actual input box, it doesn't give work anymore. Is there something weird with my HTML or JS? Thanks!
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title> Change calculator</title>
</head>
<body>
<form>
How much does the item cost? <input type="number" id="price" name ="price"/>
<br/> <br/>
How much cash do you have? <input type="number" id="cash" name="cash"/><br/> <br/>
<input type="button" value="Enter" onclick="confirmItems();"/>
</form>
<p id="confirmation"></p>
<p id ="change"></p>
</body>
var itemCost = document.getElementById("price");
var cash = document.getElementById("cash");
var confirmation = document.getElementById("confirmation");
function confirmItems() {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.value + " and you have $" + cash.value + " to pay for it.";
createConfirmationBtn();
}
function createConfirmationBtn() {
let confirmationBtn = document.createElement("BUTTON");
const confirmationBtnText = document.createTextNode("Confirm");
confirmationBtn.appendChild(confirmationBtnText);
confirmation.appendChild(confirmationBtn);
confirmationBtn.onclick = function() {
confirmValues();
}
}
let changeEl = document.getElementById("change");
function confirmValues() {
if (parseFloat(cash.value) < parseFloat(itemCost.value)) {
changeEl.innerHTML = "Not enough cash";
} else if (parseFloat(cash.value) == parseFloat(itemCost.value)) {
changeEl.innerHTML = "Your change is $0.";
} else {
calculateChange();
}
}
// cash.value = 500;
// itemCost.value = 33.44;
let remainder = parseFloat(cash.value) - parseFloat(itemCost.value);
let finalOutput = new Array();
function calculateChange() {
while (remainder > 0) {
if (remainder >= 100) {
findChange(100.00);
} else if (remainder >= 50.00) {
findChange(50.00);
} else if (remainder >= 20.00) {
findChange(20.00);
} else if (remainder >= 10.00) {
findChange(10.00);
} else if(remainder >= 5.00) {
findChange(5.00);
} else if (remainder >= 1.00) {
findChange(1.00);
} else if (remainder >= 0.25) {
findChange(0.25);
} else if (remainder >= 0.10) {
findChange(0.10);
} else if (remainder >= 0.05) {
findChange(0.05);
} else {
findChange(0.01);
}
}
changeEl.innerHTML = finalOutput;
}
function findChange(value) {
//Step 1. Get number of dollar for each type of dollar
let dValue = parseInt(remainder / value);
// Step 2. Storing numDValue in an array
finalOutput.push("[$" + value + " x" + dValue+"]");
remainder = parseFloat(remainder - (value * dValue));
remainder = parseFloat(remainder.toFixed(2));
}
You need to have the vars inside the functions that need them or they will not pick up what the user enters
You can show and hide the confirm button
DRY, Don't Repeat Yourself
function confirmValues() {
let itemCost = document.getElementById("price").value;
let cash = document.getElementById("cash").value;
const confirmation = document.getElementById("confirmation");
const changeEl = document.getElementById("change");
const confirm = document.getElementById("confirm");
cash = isNaN(cash) || cash === "" ? 0 : +cash; // test valid input
itemCost = isNaN(itemCost) || itemCost === "" ? 0 : +itemCost;
if (cash < itemCost) {
changeEl.innerHTML = "Not enough cash";
} else {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.toFixed(2) + " and you have $" + cash.toFixed(2) + " to pay for it.";
changeEl.innerHTML = "Your change is $" + (cash - itemCost).toFixed(2);
confirm.classList.remove("hide");
}
}
.hide {
display: none;
}
<title> Change calculator</title>
<form>
How much does the item cost? <input type="number" id="price" name="price" />
<br/> <br/> How much cash do you have? <input type="number" id="cash" name="cash" /><br/> <br/>
<input type="button" value="Enter" onclick="confirmValues();" />
<input type="button" id="confirm" class="hide" value="Confirm" onclick="alert('Confirmed!')" />
</form>
<p id="confirmation"></p>
<p id="change"></p>
I've been working on my own project for a little bit, and I'm currently working on adding another button in. Now I've set it up pretty similar to the other ones, but it isn't working when I press it. For my code, the firstx2, secondx2, and first building buttons all work fine, But when you try and click on the second building button, it doesn't do anything. I probably made a small typo or missed a line, but I can't seem to find it anywhere. To get to the second building button, you have to have already clicked on both multipliers and the first building. Thanks for your help!
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost x</button>
<button id="multiply2" onclick="secondx2()" style="display:none;">x2 Multiplier. Cost: 1000</button>
<button id="secondbuild" onlcick="build2()" style="display:none;">Building 2. Cost x</button>
<script>
var points = 10099;
var pointMulti = 1;
var buyupgrade = 0;
var b1cost = 200;
var b1count = 0;
var b2cost = 1000;
var b2count = 0;
var currentpoints = setInterval(pointupdate, 500);
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + Math.round(points) + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti;
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
firstbuild.innerText = "Building 1. Cost " + b1cost;
var show2ndx2 = document.getElementById("secondx2");
multiply2.style.display = "inline";
}
}
}
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + Math.round(points) + " points!";
}
function build1() {
if (points >= b1cost) {
points -= b1cost;
b1count++;
b1cost *= 1.10;
document.getElementById("b1").innerHTML = "You have " + b1count + " of building 1!"
firstbuild.innerText = "Building 1. Cost " + Math.round(b1cost);
var build1add = setInterval(build1points, 1000);
var secondbuild = document.getElementById("secondbuild");
secondbuild.style.display = "inline";
secondbuild.innerText = "Building 2. Cost " + b2cost;
}
}
function build2() {
if (points >= b2cost) {
points -= b2cost;
b2count++;
b2cost *= 1.10;
document.getElementById("b2").innerHTML = "You have " + b2count + " of building 2!"
secondbuild.innerText = "Building 2. Cost " + Math.round(b2cost);
var build2add = setInterval(build2points, 1000);
}
}
function build1points() {
points += 1;
}
function build2points() {
points += 4;
}
function secondx2() {
if (buyupgrade == 1 && points >= 1000) {
pointMulti *= 2;
points -= 1000;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " + pointMulti;
multiply2.style.display = "none";
}
}
</script>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
<p id="b1"></p>
<p id="b2"></p>
</body>
</html>
it should be onclick not onlcick in <button id="secondbuild" onlcick="build2()" style="display:none;">Building 2. Cost x</button>
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost x</button>
<button id="multiply2" onclick="secondx2()" style="display:none;">x2 Multiplier. Cost: 1000</button>
<button id="secondbuild" onclick="build2()" style="display:none;">Building 2. Cost x</button>
<script>
var points = 10099;
var pointMulti = 1;
var buyupgrade = 0;
var b1cost = 200;
var b1count = 0;
var b2cost = 1000;
var b2count = 0;
var currentpoints = setInterval(pointupdate, 500);
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + Math.round(points) + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti;
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
firstbuild.innerText = "Building 1. Cost " + b1cost;
var show2ndx2 = document.getElementById("secondx2");
multiply2.style.display = "inline";
}
}
}
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + Math.round(points) + " points!";
}
function build1() {
if (points >= b1cost) {
points -= b1cost;
b1count++;
b1cost *= 1.10;
document.getElementById("b1").innerHTML = "You have " + b1count + " of building 1!"
firstbuild.innerText = "Building 1. Cost " + Math.round(b1cost);
var build1add = setInterval(build1points, 1000);
var secondbuild = document.getElementById("secondbuild");
secondbuild.style.display = "inline";
secondbuild.innerText = "Building 2. Cost " + b2cost;
}
}
function build2() {
if (points >= b2cost) {
points -= b2cost;
b2count++;
b2cost *= 1.10;
document.getElementById("b2").innerHTML = "You have " + b2count + " of building 2!"
secondbuild.innerText = "Building 2. Cost " + Math.round(b2cost);
var build2add = setInterval(build2points, 1000);
}
}
function build1points() {
points += 1;
}
function build2points() {
points += 4;
}
function secondx2() {
if (buyupgrade == 1 && points >= 1000) {
pointMulti *= 2;
points -= 1000;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " + pointMulti;
multiply2.style.display = "none";
}
}
</script>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
<p id="b1"></p>
<p id="b2"></p>
</body>
</html>
I think you should check your button(secondbuild)
the keyword onclick is wrong
Spelling Mistake. onclick not oncilck.
<button id="secondbuild" onlcick="build2()" style="display:none;">Building 2. Cost x</button> <script>
i'm a teacher and have just started learning to code for making online quizzes for my students. I'm still very new to programming like JavaScript and php, and I've tried to looked for sources online to help create my quizzes. I have 2 questions:
1). I've set a timer for the quiz but everytime when the time is up, it just keeps counting, what should I put in the
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "";
section to redirect my student to the result page or other pages?
(2) My quizzes are mostly fill-in-the-blanks questions and I wonder how to store the point of each question and then show the total score to my students at the end of the quiz? Many thanks!.
Here's my code:
<html>
<head>
<script language ="javascript" >
var tim;
var min = 0;
var sec = 30;
var f = new Date();
function f1() {
f2();
document.getElementById("starttime").innerHTML = "Your started your quiz at " + f.getHours() + ":" + f.getMinutes();
}
function f2() {
if (parseInt(sec) > 0) {
sec = parseInt(sec) - 1;
document.getElementById("showtime").innerHTML = "Your Left Time is :"+min+" Minutes ," + sec+" Seconds";
tim = setTimeout("f2()", 1000);
}
else {
if (parseInt(sec) == 0) {
min = parseInt(min) - 1;
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "www.rawlanguages.com";
}
else {
sec = 60;
document.getElementById("showtime").innerHTML = "Your Left Time is :" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
}
}
}
}
</script>
<title>Quiz</title>
<h1>P.1 Grammar Quiz</h1>
<body>
<div id="ques0" class="ques">
<h2>Question</h2>
<p>She
<input type="text" name="answer0"/> a girl.</p>
</div>
<div id="ques1" class="ques">
<h2>Question</h2>
<p>"is", "am" and "are" are</p>
<ul>
<li>
<input type="radio" name="answer1" value="Present tense" />
<label>Present tense</label>
</li>
<li>
<input type="radio" name="answer1" value="Past tense" />
<label>Past tense</label>
</li>
<li>
<input type="radio" name="answer1" value="Future tense" />
<label>Future tense</label>
</li>
</ul>
</div>
<div id="ques2" class="ques">
<h2>Question</h2>
<p>He
<input type="text" name="answer2"/> a policeman.
</p>
</div>
Check answer!
<script src="JQ.js"></script>
<script src="function.js"></script>
<body onload="f1()" >
<form id="form1" runat="server">
<div>
<table width="100%" align="center">
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<div id="starttime"></div>
<div id="endtime"></div>
<div id="showtime"></div>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</head>
</html>
Your code is good enough for a beginner but it requires some improvements.
<script type="text/javascript" >//language ="javascript" is obsolete
//var tim; //no need at all
//var min = 0; //no need at all
//var sec = 30; //there is better way
//var f = new Date(); //no need to be global
function f1(sec) {//define (declare) sec as parameter
f2(); //call the function
var f = new Date();
document.getElementById("starttime").innerHTML = "Your started your quiz at " + f.getHours() + ":" + f.getMinutes();
var showtime = document.getElementById("showtime"); //used many times
//Here we put (closure) f2
function f2() {
//f2 knows sec from parent scope
if (sec <= 0) {//parseInt(sec) no need. sec is int
showtime.innerHTML = 'Time is over';
//ShowAnswers(); //show on the same page or post to .php
return;
}
sec--;// = parseInt(sec) - 1;
showtime.innerHTML = "Your Left Time is :" + Math.floor(sec / 60) +" Minutes ," + (sec % 60) +" Seconds";
setTimeout(f2, 1000);//"f2()" is correct but this way is better
/* no need in remaining code
}
else {
if (parseInt(sec) == 0) {
min = parseInt(min) - 1;
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "www.rawlanguages.com";
}
else {
sec = 60;
document.getElementById("showtime").innerHTML = "Your Left Time is :" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
}
}
}
*/
}//f2
}//f1
</script>
<body onload="f1(90)"><!--Here we send seconds to the function -->
Also note that all your quiz starting from <h1>P.1... must be inside body container.
I'm trying to create a script to keep a history track of three for a random number generator. (this is all for practice to take more advance approach) but I for some reason cannot get jQuery to Append a new html table/row after the code starts executing from a different JS file. however everything seems to go according to plan besides the part when I am trying to add the row into the table. I have a jsfiddle here:
http://jsfiddle.net/e3ey2a3s/2/
Here is my code however:
convert.js (the generator)
var min, max, setDol = false,
pArry = [];
function chooseRandom() {
min = prompt('whats the max value?', 'max');
max = prompt('whats the min value?', 'min');
return convertType(min, max);
}
function convertType(min, max) {
if (typeof min === 'string' || typeof max === 'string') {
document.getElementById('convert').innerHTML = "converting strings to numbers..."
parseInt(min);
parseInt(max);
}
return getRandom(min, max);
}
function getRandom(min, max) {
if (isNaN(min) || isNaN(max)) {
borked();
} else {
return amtFixed(Math.random() * (max - min) + min);
}
}
function amtFixed(amt) {
if (amt >= 0 && amt <= 10) {
document.getElementById('text').innerHTML = "Our number is " + amt + " which is between 0 and 10";
} else if (amt >= 11 && amt <= 20) {
document.getElementById("text").innerHTML = "Our number is " + amt + " which is between 11 and 20";
} else {
document.getElementById("text").innerHTML = "Our number is " + amt + " which is greater than 20. huh.";
}
var fixed = Number(amt).toFixed(2);
return convertFix(fixed);
};
function convertFix(fixed) {
if (typeof fixed === 'string') {
fixed = (fixed / 1);
document.getElementById("fixed").innerHTML = typeof fixed + " " + fixed + " converted down to two decimals.";
setDol = confirm("Convert our amount to a dollar amount?");
} else {
console.log('Failed to convert...');
}
return success(fixed);
};
function borked() {
var broke = false;
alert("You must not of entered a proper number... That sucks :/");
var broke = confirm("Do you want to retry?");
if (broke) {
return chooseRandom();
} else {
return document.getElementById("text").innerHTML = "I r broked :(";
}
}
function success(num) {
var amtHist = [];
if (setDol) {
$("#price").append('$' + num + ' Set fixed to a dollar amount!');
pArry.push(num);
return buildHistory(pArry);
} else {
$("#price").empty().append("Our fixed value is: " + num);
pArry.push(num);
return buildHistory(pArry);
}
}
After this script finishes up success() send the finished array over to my data.js function buildHistory() which looks like this:
buildHistory = function(arr) {
var t, i, _this = this,
numEls = 0,
a = arr;
var objLen = holdObj.History.length;
table = $('table.history');
//Let's do our loops to check and set history data
//We need to get our history data so we can make sure not to re print old data.
for (t = 0; t <= objLen; t++) {
for (i = 0; i < a.length; i++) {
x = objLen[t];
if ($.inArray(x, a) === -1) {
//Alright now we build onto the history table
$('table.history').append('<tr><td>' + a[i] + '</td></tr>');
var cell = table.find('td');
cell.addClass('hist' + numEls);
numEls++;
holdObj.History.push(a[i]);
} else {
break;
}
}
}
// Let's remove the oldest value once the table exceeds 3 or 4.
if (objLen > 3 && numEls > 3) {
var tmp = table.find('hist_3');
table.remove(tmp);
holdObj.History.pop();
}
}
This is all still in the makes so nothing is really finalized here, I am probably just overlooking a simple solution.
Here is my HTML:
<html>
<head>
<script type="text/javascript" src="../source/libs/jQuery-1.8.3.min.js"></script>
<title>Index</title>
</head>
<body>
<p>This is just some filler content lol.</p>
<p>Let's run some scripts! Click the buttons!</p>
<div class="math">
<p id="convert"></p>
<p id="text"></p>
<p id="fixed"></p>
<p id="price"></p>
<table id="history">
<tr>
<th>History</th>
</tr>
<tr>
<td id="hist"> Value #1</td>
</tr>
</table>
</div>
<button class="scrBtn">Click to start Script</button>
<div id="date"></div>
<button class="dateBtn">Get Date</button>
<div class="person">
<div class="pTitle">
<div class="pBody">
<div class="fName">Name: </div>
<div class="age">Age: </div>
<div class="height">Height: </div>
<div class="eyecolor">Eye Color: </div>
<div class="sex">Sex: </div>
This is where our person should go.
</div>
</div>
</div>
<a href="view/Form/personForm.html">
<button class="pBtn">Get Info</button>
</a>
<div class="bRowLeft">test
</div>
<div class="tRowLeft">test
</div>
</body>
<script type="text/javascript" src="../source/model/data.js"></script>
<script type="text/javascript" src="../source/model/convert.js"></script>
<script type="text/javascript" src="../source/model/button.js"></script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</html>
Sorry for such a long post but I am trying to explore as much as I can.
(The code is activated via jQuery with button.js)
$(document).ready(function() {
$('.scrBtn').click(function() {
chooseRandom();
});
});
Thanks again, let me know if anymore information is needed.
$('table.history') - you dont have a <table class="history"> element.
Try this:
table = $("#history");
and same where you append.