Why doesn't my script work with checkboxes? - javascript

I am trying to make a little "game" and for some reason, if I try and get the checked of a checkbox, my script will flip out... sometimes it works, sometimes it just stops executing. Is there some sort of an error I missed?
<html>
<head>
<title>Untitled Document</title>
<script>
var check = "showcheck";
var number = 1234;
var lvl = 1;
var oldlvl = 1;
var multiplier = 10000;
var start = 1;
function exefunction() {
document.getElementById("boxv").focus();
if (check == "showcheck") {
document.getElementById("message").innerHTML = "What was the number?";
document.getElementById("num").style.display = "none";
document.getElementById("box").style.display = "inline";
document.getElementById("boxv").focus();
check = "checknum";
}
else if (check == "checknum") {
if (document.getElementById("boxv").value == number) {
document.getElementById("message").innerHTML = "CORRECT!";
document.getElementById("boxv").style.color = "#00DD00";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
lvl++;
}
else if (document.getElementById("boxv").value != number) {
document.getElementById("message").innerHTML = "INCORRECT!";
document.getElementById("boxv").style.color = "#DD0000";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
if (lvl>1) {lvl--;}
loselife();
}
check = "showmem";
}
else if (check == "showmem") {
if (lvl == oldlvl + 10) {
oldlvl = lvl;
multiplier = multiplier * 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
else if (lvl < oldlvl) {
oldlvl = lvl - 10;
multiplier = multiplier / 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
number = Math.floor(Math.random() * multiplier / 10 * 9) + multiplier / 10;
document.getElementById("boxv").style.color = "#000000";
document.getElementById("boxv").value = "";
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").innerHTML = number;
document.getElementById("num").style.display = "inline";
document.getElementById("box").style.display = "none";
check = "showcheck";
}
}
function loselife(){
var life = 4;
var hearts = "♥ ";
alert(document.getElementById("lifebox").checked);
}
function submitenter() {
var keycode = window.event.keyCode;
if (keycode == 13) {
if (start === 0) {exefunction();}
else {startfunc();}
}
if (keycode < 47 || keycode > 58) {
return false;
}
}
function startfunc() {
document.getElementById("button").innerHTML = '<input name="" type="button" value="OK" onClick="exefunction()"/>';
document.getElementById("level").innerHTML = "Level: " + lvl;
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").style.display = "inline";
document.getElementById("boxv").value = "";
document.getElementById("box").style.display = "none";
if (document.getElementById("lifecheck").checked === true) {
document.getElementById("life").innerHTML = "♥ ♥ ♥ ♥ ♥ ";
}
else if (document.getElementById("lifecheck").checked === false) {
document.getElementById("life").innerHTML = "";
}
if (document.getElementById("timercheck").checked === true) {
document.getElementById("timer").innerHTML = "3:00";
}
else if (document.getElementById("timercheck").checked === false) {
document.getElementById("timer").innerHTML = "";
}
start = 0;
}
function tests() {
alert(lfckv);
}
</script>
<style type="text/css">
#level, #life, #timer{
color: #666;
}
* {
text-align: center;
}
#num {
display: none;
}
#num {
font-size: x-large;
}
#body {
margin-top: 250px;
margin-right: auto;
margin-bottom: 100px;
margin-left: auto;
}
body {
background-color: #6FF;
}
</style></head>
<body onKeyPress="return submitenter()" >
<div id="body">
<span id="level"></span>
<table align="center">
<tr>
<td width="200" height="50" align="center" valign="middle"><span id="message">What level would you like to begin at?</span></td>
<td width="200" height="50" align="center" valign="middle"><span id="num">1234</span><span id="box"><input type="text" id="boxv" maxlength="4" value="1"/></span></td>
</tr>
</table>
<table align="center">
<tr>
<td width="200" id="life"><label><input id="lifecheck" type="checkbox" >Lives</label></td>
<td id="button"><input type="button" value="OK" onClick="startfunc()"/></td>
<td width="200" id="timer"><label><input id="timercheck" type="checkbox" >Timer</label></td>
</tr>
</table>
<input name="" type="button" onClick="tests()" value="tests()">
</div>
</body>
</html>

lifebox isnt defined in the loselife() function. Plus, also check the test() function, that alert() statement has a variable that isnt defined.
If you are using Google chrome (or any other browser that can help you debug), I would suggest you to debug through your lines of code.

I think you're better off using simple equality for checking the state of your checkboxes, because I'm pretty the outcome is not a Boolean.
So it would be something like that :
if (document.getElementById("lifecheck").checked == true) {
or simply
if (document.getElementById("lifecheck").checked) {
instead of
if (document.getElementById("lifecheck").checked === true) {

Ahah! I figured out the problem. Apparently, when I set the visibility of the checkbox to none, it also set the checkvalue to null for some reason. I had expected it to keep the checkvalue, but for some reason it does not.

Related

Javascript for card shuffle failing

Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}

How to save multiple user inputs into new variables

Im creating a guessing game and the user has 5 attempts to make the correct guess. I want to save their previous guesses (inputs) to show it to them. I have been using the snippet below to save one attempt when the user types into an <input> field, but how can I save the next 4 attempts in new variables such as userGuess2, userGuess3, etc.
var userGuess = document.getElementById("inputField").value;
$('#previousGuesses').text(userGuess);
Ok then let's pretend this is your input
<input type="text" id="inputField">
You can create an index that will increment everytime the users presses enter to save another answer
var i=1;
And the id name your autogenerated spans will have
var name = "previousGuesses";
Now on your function you will save the value when the user presses enter like you described and when that happens it will create a new span element where it will display the value stored
function myFunction(){
$("#inputField").keypress(function( event ) {
if ( event.which == 13 || event.which == 9) {
var userGuess = document.getElementById("inputField").value;//get value of the answer
var span = document.createElement('SPAN');//create a new span
span.innerHTML = userGuess + "<br>";//answer value goes here
span.id = name+i;//this is the id of your new span, remember ids are unique so we attach var i to the name var we declared before
document.body.appendChild(span);
//$('#previousGuesses'+i).text(userGuess);
i++;
}
});
}
now call your function
myFunction();
https://jsfiddle.net/kenpy/m16bojhg/4/
You can just simply add an element for the user's last attempts and add to it.
f(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
guessField.focus();
function checkGuess() {
var userGuess = Number(guessField.value);
if(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if(userGuess === randomNumber) {
lastResult.textContent = "Good job! You win!";
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if(guessCount === 10) {
lastResult.textContent = 'Hahaha You suck!';
lowOrHi.textContent = '';
setGameOver();
} else {
lastResult.textContent = "Oops! You're Wrong!";
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
console.log('cheat is: ' + randomNumber);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Play Again?';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for(var i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
body{
background-image: linear-gradient(to left top, #c6fced, #a3efda, #7fe3c7, #54d5b3, #00c89f);
color: #2F3139;
margin: 10rem auto;
height:50vh;
}
h1 {
font-size: 1.5rem;
}
.lastResult {
color: white;
padding: 3px;
}
button {
margin-left:3rem ;
}
<h3 class="display-4 text-center text-muted text-capitalize"></h3>
<div class="container">
<div class="row">
<div class="col-md-6 ">
<h1 class="text-muted text-capitalize">
<span class="text-primary">JavaScript</span> Number guessing game</h1>
<p class="lead">Simply enter a number between 1 - 100 then click the button</p>
</div>
<div class="col-md-6">
<div class="mt-4 d-inline-block">
<div class="form">
<label for="guessField">Guess a number : </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas text-center lead">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</div>
</div> </div>
</div>
Resource
JavaScript number guessing game

for loop printing only last item in array of objects

Guys i am in a trouble here. I made a table of songs, then i inserted them in local storage, and now i want to search the items in local storage to see if a name of an album exists in local storage(in a table) or not, i made this .js code and when i try to search for items in local storage(objects in array), for example i try searching for california and it prints "NO" but there is one in local storage called california, but when i search for chuck it prints "YES", and if i add one more it will do the same, it will print only the last item in this array, why is this happening. Thanks in advance.
let ls = [{
name: "california",
artist: "blink182",
year: 2016,
num: 28
},
{
name: "chuck",
artist: "sum41",
year: 2004,
num: 13
}
];
localStorage.setItem("songs", JSON.stringify(ls));
document.getElementById("btn").addEventListener("click", search);
function search(e) {
JSON.parse(localStorage.getItem("songs"));
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
for (let i = 0; i < ls.length; i++) {
if (inputVal === ls[i].name) {
outputVal.innerHTML = "YES";
} else {
outputVal.innerHTML = "NO";
}
}
e.preventDefault();
}
body {
background-color: lime;
line-height: 1.5;
font-size: 15px;
margin: auto;
width: 80%;
}
table,
th,
td {
border: 2px solid black;
padding: 20px;
}
div {
margin: 50px;
}
<table>
<tr>
<th>Name of album</th>
<th>Artist</th>
<th>Year</th>
<th>numOfTracks</th>
</tr>
<tr>
<td>California</td>
<td>Blink 182</td>
<td>2016</td>
<td>28</td>
</tr>
<tr>
<td>Chuck</td>
<td>Sum 41</td>
<td>2004</td>
<td>13</td>
</tr>
</table>
<form id="myForm">
<p>Search LS</p>
<input type="text" id="input">
<button type="submit" id="btn">Search</button>
</form>
<div id="output"></div>
The problem is that you're setting the HTML of the div to YES/NO. Which is being overridden in the next iteration that's why you feel like it's printing for the last item in the list. Instead you need to append to what's already there
for (let i = 0; i < ls.length; i++) {
if (inputVal === ls[i].name) {
outputVal.innerHTML = outputVal.innerHTML + " YES" ;
} else {
outputVal.innerHTML = outputVal.innerHTML + " NO";
}
}
Now you should be able to see YESNO for the list values
function search(e) {
JSON.parse(localStorage.getItem("songs"));
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
var resultExists = false;
var resultCount = 0;
for (let i = 0; i < ls.length; i++) {
if (inputVal === ls[i].name) {
// Case 2
resultExists = true;
resultCount++;
// Updated your case
// outputVal.innerHTML = "YES";
// break;
}
//else {
// outputVal.innerHTML = "NO";
//}
}
// Case 2
if(resultExists){
outputVal.innerHTML = "YES";
// Do anithing with resultCount if you need
}else{
outputVal.innerHTML = "NO";
}
e.preventDefault();
}
It's printing all the items but you are overwriting the innerHTML value each time instead of adding to it, see the edit below.
let ls = [{
name: "california",
artist: "blink182",
year: 2016,
num: 28
},
{
name: "chuck",
artist: "sum41",
year: 2004,
num: 13
}
];
// localStorage.setItem("songs", JSON.stringify(ls));
document.getElementById("btn").addEventListener("click", search);
function search(e) {
// JSON.parse(localStorage.getItem("songs"));
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
/* note the use of += instead of = */
for (let i = 0; i < ls.length; i++) {
if (inputVal === ls[i].name) {
outputVal.innerHTML += "YES";
} else {
outputVal.innerHTML += "NO";
}
}
e.preventDefault();
}
body {
background-color: lime;
line-height: 1.5;
font-size: 15px;
margin: auto;
width: 80%;
}
table,
th,
td {
border: 2px solid black;
padding: 20px;
}
div {
margin: 50px;
}
<table>
<tr>
<th>Name of album</th>
<th>Artist</th>
<th>Year</th>
<th>numOfTracks</th>
</tr>
<tr>
<td>California</td>
<td>Blink 182</td>
<td>2016</td>
<td>28</td>
</tr>
<tr>
<td>Chuck</td>
<td>Sum 41</td>
<td>2004</td>
<td>13</td>
</tr>
</table>
<form id="myForm">
<p>Search LS</p>
<input type="text" id="input">
<button type="submit" id="btn">Search</button>
</form>
<div id="output"></div>
I would try something like this:
function search(e) {
let songs = JSON.parse(localStorage.getItem("songs"));
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
outputVal.innerHTML = dataContainsField(ls, inputVal) ? "YES" : "NO";
e.preventDefault();
}
function dataContainsField(data, field) {
for (let i = 0; i < data.length; i++) {
if (field === data[i].name) return true;
}
return false;
}
Putting the logic to check for the existence of the data in your dataset into a function makes it easier to code and decouples that logic from your search function.
As you're using for loop that's why every time it is just overwriting you value with last value. You can try like this with Array.prototype.find(). Also you've some issue with your localStorage data parsing inside your search(e) function, here you're not storing it to ls variable before doing any find/search operation
See working demo https://jsfiddle.net/ttr80ona/
let ls = [{name: "california",artist: "blink182",year: 2016,num: 28},{name: "chuck",artist: "sum41",year: 2004,num: 13}];
localStorage.setItem("songs", JSON.stringify(ls));
document.getElementById("btn").addEventListener("click", search);
function search(e) {
let ls = JSON.parse(localStorage.getItem("songs")); //I've modified here
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
var status = ls.find(elm => elm.name === inputVal);
if (status)
outputVal.innerHTML = "YES";
else
outputVal.innerHTML = "NO";
e.preventDefault();
}
The problem is you are overriding yes with no. You should set default to false and make it true once found or remove else condition.
function search(e) {
JSON.parse(localStorage.getItem("songs"));
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
let bFound = false;
for (let i = 0; i < ls.length; i++) {
if(inputVal === ls[i].name) {
bFound = true;
break;
}
}
outputVal.innerHTML = bFound ? "YES" : "No";
e.preventDefault();
}

Checkers game - how to remove img or checker piece after a jump over

Just did a simple game of checkers, got the logic done of jumping or moving the checker pieces.
Now having problems on the actual logic of when a checker piece moves over or jumps over the other checker piece. How do i automatically remove or delete the checker piece that was jumped over?
Thanks so much :)
<html>
<head>
<style>
body { background-color: #D1CDDF; }
p { font-family: Verdana, Geneva, sans-serif;
font-size: 30; }
img { width: 35px;
height: 35px; }
label { font-family: "Lucida Console", Monaco, monospace;
font-size: 15; }
.focused{ border: 2px solid yellow; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var moves = [];
function saveScore() {
// syntax: $.post(URL,data,callback);
$.post("scores.php",
{
TheFile: $("#filename").val(),
TheMessage: $("#winner").val() + "\r\n"
}
,function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
function openBoard()
{
$(document).ready(function()
{
var p1Name = document.getElementById("p1name").value;
var p2Name = document.getElementById("p2name").value;
var heading = "<center><p><font color=\"red\"><b>" + p1Name + "</b></font> vs <font color=\"blue\"><b>" + p2Name + "</b></font></p></center>";
var table = $('<table width=500px cellspacing=0px cellpadding=0px border=1px ></table>');
var rc;
var picName;
var picName2;
for( y = 1; y <= 8; y++ )
{
var row = $('<tr></tr>');
for ( var x = 1; x <= 8; x++)
{
rc = y + x;
// creating the images
picName = "p" + 1 + ".png" ;
var pic1 = $('<img>').attr('src',picName);
picName2 = "p" + 2 + ".png";
var pic2 = $('<img>').attr('src',picName2);
if(rc % 2 === 0)
{
if(y === 1 || y === 2 || y === 3)
{
var col1 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
col1.html(pic1);
row.append(col1);
}
else if(y === 6 || y === 7 || y === 8)
{
var col2 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
col2.html(pic2);
row.append(col2);
}
else
{
var col3 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
row.append(col3);
}
}
else
{
var col4 = $('<td align=center height=50px width=50px bgcolor=#C4C160 ></td>');
row.append(col4);
}
}
table.append(row);
}
document.getElementById("bBoard").style.visibility = "hidden";
$('#board').append(heading);
$('#board').append(table);
// setting the listener
$('td').click(function()
{
iAmtheClickListener(this.id);
});
});
}
function iAmtheClickListener(theID)
{
var r = $.inArray(theID,moves); // determine if the id is in the array
var content = $("#"+theID).html();
if( ((r < 0) && (content !== "")) || ((r<0) && (moves.length == 1)) )
{
moves.push(theID);
//change background color
changeBackground("#"+theID,"yellow");
}
else
{
moves.splice(r,1); // to remove
changeBackground("#"+theID,"#4E9660") ;
}
if (moves.length == 2)
{
var destId = moves[1] ;
var srcId = moves[0] ;
var srcImg = $("#" + srcId).html();
$("#" + destId).html(srcImg);
$("#" + srcId).html("");
moves = [] ; // remove all
changeBackground("#"+destId,"#4E9660") ;
changeBackground("#"+srcId,"#4E9660") ;
}
$('#result').html(theID);
}
function changeBackground(theIdUwant, theColor)
{
$(theIdUwant).css("background-color",theColor);
}
</script>
</head>
<body>
<center>
<p>~Checkers~</p>
<table border=1 cellpadding=25px>
<tr><td><label>Player 1: <input type=text id=p1name /></label><br/><br/>
<label>Player 2: <input type=text id=p2name /></label><br/><br/>
<button id="bBoard" onclick="openBoard();">Start Game</button><br/><br/></td>
<td><div class="b" id="board"></div></td>
<td>
<input type=hidden id=filename value="players.txt" />
<label>Register Winner: <input type=text id=winner /></label><br/><br/>
<button id="bReg" onclick="saveScore();">Submit</button><br/><br/>
<div id="result"></div>
</td>
</td></tr>
</table>
</center>
</body>
Suppose jumped piece is at board[row][col], you can assign a value of zero or empty at that particular cell after being jumped:
board[row][col] = EMPTY

How to roll one dice at a time?

So here is what I have so far. I am very new to javascript. How do I make these dice roll sequentially inside of the divs? Such as only displaying the next random number only after the first one is displayed.
<html>
<style>
.numdiv{
height: 400px;
width: 200px;
border:solid 1px green;
float: left
}
</style>
<head>
<script>
function rollDice(){
var number1 = document.getElementById("number1");
var number2 = document.getElementById("number2");
var number3 = document.getElementById("number3");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var d3 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2 + d3;
number1.innerHTML = d1;
number2.innerHTML = d2;
number3.innerHTML = d3;
status.innerHTML = "You rolled "+diceTotal+".";
if(diceTotal == 15){
status.innerHTML += "You Win!!";
}
}
</script>
</head>
<body>
<table>
<tr>
<td>
<div class="numdiv" id="number1">
0</div>
<div class="numdiv" id="number2">
0</div>
<div class="numdiv" id="number3">
0</div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()"/>Generate Number</button></td></tr>
<tr>
<td><span id="status">0</span></td></tr>
</table>
</body>
</html>
You can use the setTimeout() method to delay execution of a function, so that the dice will be rolled one at a time:
function rollDice(){
var status = document.getElementById("status");
var nums = document.querySelectorAll(".numdiv");
var diceTotal = 0;
var current;
for (current = 0; current < nums.length; current++) {
nums[current].innerHTML = "?";
}
current = 0;
status.innerHTML = "Rolling...";
function rollNext() {
currentRoll = Math.floor(Math.random() * 6) + 1;
nums[current].innerHTML = currentRoll;
diceTotal += currentRoll;
current++;
if (current < nums.length) {
setTimeout(rollNext, 1000);
} else {
status.innerHTML = "You rolled " + diceTotal + ".";
if(diceTotal == 15){
status.innerHTML += "You Win!!";
}
}
}
setTimeout(rollNext, 1000);
}
.numdiv { height: 30px; width: 30px; border:solid 1px green; float: left; margin: 10px }
<table>
<tr>
<td>
<div class="numdiv" id="number1"></div>
<div class="numdiv" id="number2"></div>
<div class="numdiv" id="number3"></div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()"/>Generate Number</button></td></tr>
<tr>
<td><span id="status">0</span></td>
</tr>
</table>
Notice also that I've removed your separate number1, number2 and number3 variables, instead using a single variable num to refer to the list of all of the .numDiv div elements. That way you can easily change how many dice you want to use without changing the JS at all (you'd just add or remove .numDiv elements).
EDIT: As I was posting the above you clarified that you want the user to press the button for each die, not automatically roll all three with a delay. So I guess, maybe something like the following, keeping a counter and the total in variables declared outside the function:
var statusSpan = document.getElementById("status");
var nums = document.querySelectorAll(".numdiv");
var diceTotal;
var current = 0;
function rollDice(){
if (current === 0) { // reset display
for (var i = 0; i < nums.length; i++)
nums[i].innerHTML = "?";
diceTotal = 0;
}
currentRoll = Math.floor(Math.random() * 6) + 1;
nums[current].innerHTML = currentRoll;
diceTotal += currentRoll;
if (++current < nums.length) {
statusSpan.innerHTML = "Current total: " + diceTotal + ".";
} else {
statusSpan.innerHTML = "You rolled " + diceTotal + ".";
if(diceTotal == 15){
statusSpan.innerHTML += "You Win!!";
}
current = 0;
}
}
.numdiv { height: 30px; width: 30px; border:solid 1px green; float: left; margin: 10px; text-align: center }
<table>
<tr>
<td>
<div class="numdiv" id="number1"></div>
<div class="numdiv" id="number2"></div>
<div class="numdiv" id="number3"></div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()">Roll next die</button></td></tr>
<tr>
<td><span id="status">Ready to roll?</span></td>
</tr>
</table>
Create a counter variable starting with one outside of your rollDice function and every time that is clicked then increase the counter by one. Then you need to replace all the number variables with just this:
var number = document.getElementById("number" + counter);
I think you know where to go from here. Let me know if you need more guidance!
Building on your existing logic, if you want to display 1 every time user clicks then an alternate approach....
var totalIter = 0;//global var which is set to increments on each click
var diceTotal = 0;
function rollDice() {
totalIter = totalIter + 1; //increment by 1
//Existing logic from your script
var ele = document.getElementById("number" + totalIter);
var d1 = Math.floor(Math.random() * 6) + 1;
var status = document.getElementById("status");
diceTotal = diceTotal + d1;
ele.innerHTML = d1;
status.innerHTML = "You rolled " + diceTotal + ".";
if (diceTotal == 15) {
status.innerHTML += "You Win!!";
}
}

Categories