I need help with this app. I want the user to choose a name, color and number. When the form is submitted, boxes of the chosen color and number are generated. More boxes can be added and the originals are not erased. Each box has random positioning and a unique id.
Here is my effort: http://jsfiddle.net/christopherpl/gnVj6/
//Invoke functions only after page has fully loaded
window.onload = init;
//Create an array that will be populated by the user generated boxes
var boxes = [];
//Create a global counter variable that keeps track of the number of
//boxes generated
var counter = 0;
//Create a Box constructor function with parameters, to create box objects
//for each box that's generated
function Box(id, name, color, x, y) {
this.id = id;
this.name = name;
this.color = color;
this.x = x;
this.y = y;
}
//Set up the onclick event handler for the generate button input
function init() {
var generateButton = document.getElementById("generateButton");
generateButton.onclick = generate;
var clearButton = document.getElementById("clearButton");
clearButton.onclick = clear;
}
//Get boxes' name from user
function generate() {
var data = document.forms.data;
var textInput = document.getElementById("name");
var name = textInput.value;
if (name == null || name == "") {
alert("Please give your Amazing Box a name");
return;
}
//Get color option from user
var colorSelect = document.getElementById("color");
var colorOption = colorSelect.options[colorSelect.selectedIndex];
var color = colorOption.value;
if (!color) {
alert("Pick a color");
return;
}
//Get number of boxes to be generated from user
var amountArray = data.elements.amount;
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
//Create and append the new <div> element
var div = document.createElement("div");
//Randomly position each <div> element
var x = Math.floor(Math.random() * (scene.offsetWidth-101));
var y = Math.floor(Math.random() * (scene.offsetHeight-101));
//Give each <div> element a unique id
var newId = div;
newId = counter++;
id = newId;
//Add the style, including the background color selected
//by the user.
div.style.left = x + "px";
div.style.top = y + "px";
div.style.backgroundColor = color;
div.setAttribute("class", "box");
scene.appendChild(div);
div.innerHTML = "Box of " + name + "<br />(click me)";
//Create an onclick event displaying the
//details of each box generated
div.onclick = function() {
alert("You clicked on a box with id " + id +
", named Box of " + name + ", whose color is " + color +
" at position " + div.style.top + ", " + div.style.left)
}
//Form reset
data = document.getElementById("data");
data.reset();
}
}
}
//Clear the boxes from scene div
function clear() {
var sceneDivs = document.querySelectorAll("div#scene div");
for (var i = 0; i < sceneDivs.length; i++) {
var scene = document.getElementById("scene");
var cutList = document.getElementsByTagName("div")[1];
scene.removeChild(cutList);
}
}
In your code, when you do this loop:
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
/* make the div */
}
}
You are always just making one box. What you need to do is a second loop, using the value of the radio button as the length of the loop. Something like:
var totalBoxes = 0;
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
totalBoxes = amountArray[i].value;
}
}
for (i = 0; i < totalBoxes; i++) {
/* make the div */
}
That way you will get 5 boxes if the user checked the 5 box, and so on.
Related
I am very new to Javascript, and have a question about one of my functions(checkOrBet). I am trying to make a Texas Hold'em poker game, and the part that doesn't seem to be working is where I test for a regular pair. It doesn't seem to recognize that a pair has been made, when the cards are dealt to the deck.
function game() {
function Playert(name, chips) {
this.name = name;
this.chips = chips;
this.firstCard = [];
this.secondCard = [];
this.blind = {};
// this.turnpos = 0; //1 for current turn
//will be computer's response when prompted during the flop
this.checkOrBet = function checkOrBet() {
var response;
//Ace High
if (this.firstCard.rank == "A") {
response = "call";
console.log("Ace High!");
} else if (this.secondCard.rank == "A") {
response = "call";
console.log("Ace High!");
}
//Tests for a pocket pair
if (this.firstCard.rank == this.secondCard.rank) {
response = "call";
console.log("Pocket pairs!");
}
//Test for a regular pair
if (this.firstCard.rank == communityCards.cards[0].rank || communityCards.cards[1].rank || communityCards.cards[2].rank) {
response = "call";
console.log("pairs");
} else if (this.secondCard.rank == communityCards.cards[
0]) {
response = "call";
console.log("pairs");
}
}
}
function Pot(chipsp) {
this.chipsp = 0;
}
//clears text every time start button is pressed
function clearBox() {
document.getElementById("computer").innerHTML = "";
document.getElementById("flop").innerHTML = "";
document.getElementById("hand1").innerHTML = "";
}
clearBox();
//players start with chips, low blind, big blind.
var computer = new Playert("Computer", 200);
var player = new Playert("Player1", 200);
//Need a deck to deal the cards for the players.
var deck = new Stack();
//player's hand
var phand = new Stack();
//computer's hand
var chand = new Stack();
//game cards
var gamehand = new Stack();
//make pot
var pot1 = new Pot();
//community cards variable
var communityCards = new Stack();
deck.makeDeck(1);
deck.shuffle(1);
//deal 2 cards to player hand
if (phand.cardCount < 2) {
alert("Not enough cards in deck");
} else {
for (i = 0; i < 2; i++) {
phand.addCard(deck.deal());
}
}
//grab player div by the ID
playerhand = document.getElementById("hand1");
//create p element to show cards in player div
var pdoc = document.createElement("p");
//create text node to append to p element
var ptext = document.createTextNode(phand.cards);
//append text node to p element
pdoc.appendChild(ptext);
//append p element with cards to the hand1 div
playerhand.appendChild(pdoc);
//deal cards to computer's hand
if (chand.cardCount < 2) {
alert("Not enough cards in deck");
} else {
for (i = 0; i < 2; i++) {
chand.addCard(deck.deal());
}
}
//tie computer's hand to firstCard/secondCard
computer.firstCard = chand.cards[0];
computer.secondCard = chand.cards[1];
console.log(computer.firstCard.rank);
console.log(computer.secondCard.rank);
//grab computer div by id
d = document.getElementById("computer");
//create p element to show cards in computer div
var cdoc = document.createElement("p");
//create text node to append to p element
var ctext = document.createTextNode(chand.cards.toString());
//append text node to p element
cdoc.appendChild(ctext);
//append p element to computer div
d.appendChild(cdoc);
//grab game cards div
g = document.getElementById("flop");
//create p element for appending
var fdoc = document.createElement("p");
//create text node to append to paragraph element
//choose which player has the blind
function blinds() {
var small = 5;
var big = 10;
var random = Math.floor(Math.random() * 2) + 1;
if (random == 1) {
player.blind = small;
player.chips -= small;
computer.blind = big;
computer.chips -= big;
pot1.chipsp += 15;
} else if (random == 2) {
player.blind = big;
player.chips -= big;
computer.blind = small;
computer.chips -= small;
pot1.chipsp += 15;
}
}
blinds();
//Show chips for player
var chips = document.getElementById("hand1");
var chipsp = document.createElement("p");
var chipsn = document.createTextNode("You have " + player.chips +
" chips");
chipsp.appendChild(chipsn);
chips.appendChild(chipsp);
//Show chips for the computer
var cchips = document.getElementById("computer");
var pchips = document.createElement("p");
var chipsnc = document.createTextNode("You have " + computer.chips +
" chips");
pchips.appendChild(chipsnc);
cchips.appendChild(pchips);
//grab computer hand div for printing out chips
function grab(x) {
d = document.getElementById(x);
return d;
}
//grab computer div
var cblind = grab("computer");
//create p element
var cpblind = document.createElement("p");
//create text node
var ctblind = document.createTextNode("Computer's blind is" + " " +
computer.blind);
//append text to p
cpblind.appendChild(ctblind);
//append p to computer div
cblind.appendChild(cpblind);
//grab hand1 for showing player blind
var ghand1 = grab("hand1");
//create element
var ghand2 = document.createElement("p");
//create text node
var ghand3 = document.createTextNode("Player's blind is" + " " + player
.blind);
//append text to para
ghand2.appendChild(ghand3);
//append p to div
ghand1.appendChild(ghand2);
//if computer gets the blind of 5,call no matter what
if (computer.blind = 5) {
computer.chips -= 5;
}
//if player is low blind, prompt for call, fold, or bet
if (player.blind == 5) {
var cfb = prompt("Would you like to call, fold, or bet?");
switch (cfb) {
case "call":
//do something
//draw 3 cards from the deck and append
for (i = 0; i < 3; i++) {
communityCards.addCard(deck.draw(1));
}
player.chips -= 5;
pot1.chipsp += 5;
chipsn.nodeValue = "You have " + player.chips + " chips";
player.turnpos = 1; //has acted
break;
case "fold":
//do something
computer.chips += pot1.chipsp;
break;
case "bet":
//do something
break;
default:
//do something
}
//start flop round
//draw 3 cards from the deck / switch statement for check,fold, bet?
//prompt computer and player on what they want to do
} else if (player.chips = 10) {
//draw 3 cards from the deck and append
for (i = 0; i < 3; i++) {
communityCards.addCard(deck.draw(1));
}
player.chips -= 5;
pot1.chipsp += 5;
}
//print flop cards to flop div
var flopc = document.getElementById("flop");
var flopcr = document.createElement("p");
var floptn = document.createTextNode(communityCards.cards.toString());
flopcr.appendChild(floptn);
flopc.appendChild(flopcr);
//print pot to flop div
var potf = document.createElement("p");
var pottn = document.createTextNode("The pot is " + pot1.chipsp);
potf.appendChild(pottn);
flopc.appendChild(potf);
//if player has acted, prompt computer to check, bet or fold
// if (player.turnpos == 1) {
//computer evaluates hands
//}
//test function
computer.checkOrBet();
}
Go with this :
//Test for a regular pair
if (this.firstCard.rank == communityCards.cards[0].rank || this.firstCard.rank == communityCards.cards[1].rank || this.firstCard.rank == communityCards.cards[2].rank) {
response = "call";
console.log("pairs");
} else if (this.secondCard.rank == communityCards.cards[
0]) {
response = "call";
console.log("pairs");
}
same for the second card.
I am confused at to why my function executes before the start button is pressed. I looked around and they said the onclick will run at the start if you don't but the code to be executed when the button is clicked in a function. But mine is a function... This code is supposed to create 4 buttons when the start button is pressed. But right now the 4 buttons appear right away.
EDIT: Here is the full code.
var log = document.getElementById("Log");
log.addEventListener("click", login); // Runs the Login Function
var email;
var password;
// Makes an alert to test input values.
function login() {
form = document.getElementById("form");
var text = "E-Mail: " + form.elements[0].value + " Password: " + form.elements[1].value;
alert (text);
}
// Testing Function
function helloWorld() {
alert ("Hello World");
}
//create the snake
function createSnake() {
var bodyLength = 5; //snake length
var body = []; //snake body
var head = [10, 10]; //snake head starting position;
// create the variables to edit for the body positions loop
var row = head[0];
var col = head[1];
// set the snake body positions
for (var i=0;i<bodyLength; i++) {
body[body.length] = [row, col];
var cord = row + "_" + col;
// Set the head Green
if (i == 0) { document.getElementById(cord).style.backgroundColor = 'green';
}
// Set the Body blue
else {document.getElementById(cord).style.backgroundColor = 'blue';}
row++;
}
}
var snakeBool = false; //Bool to test if the snake game has been pressed.
// Create a table function. Creates a gray table for Snake.
function createTable() {
if (!snakeBool) {
// create a table of data
//target the activity div
var activity = document.getElementById("activity");
//create table
var tbl = document.createElement("table");
//table styles
tbl.style.borderCollapse = "collapse";
tbl.style.marginLeft = '12.5px';
//create size var
//var size = '5px';
//set the row and column numbers
var tr_num = 30;
var td_num = 25;
//start the loops for creating rows and columns
for (var i = 0; i < tr_num; i++) {
var tr = document.createElement("tr"); // create row
//tr style
tr.style.height = '7px';
for (var j = 0; j < td_num; j++) { //start loop for creating the td
var td = document.createElement("td"); //create td
td.style.width = '5px';
if (i == 0 || i == (tr_num-1) || j == 0 || j == (td_num-1)) {
td.style.backgroundColor = "white";
}
else {
td.style.backgroundColor = "gray";
}
td.id = i + "_" + j; //set id to td
//td.appendChild("data"); //append data to td
tr.appendChild(td); //append td to row
}
tbl.appendChild(tr); //append tr to the table
}
activity.appendChild(tbl); //append the table to activity div
createSnake(); //Creates the snake body.
snakeBool = true; //Sets the Snake Bool to true since game has been created.
//create Start button
var b1 = document.createElement("input");
b1.type = "button";
b1.value = "Start";
b1.onClick = startGame;
activity.appendChild(b1);
} // end of if Function
}
function startGame() {
createButtons();
}
function createButtons() {
var b1 = document.createElement("input");
b1.type = "button";
b1.value = "Up";
//b1.onClick = func
activity.appendChild(b1);
var b2 = document.createElement("input");
b2.type = "button";
b2.value = "Down";
//b1.onClick = func
activity.appendChild(b2);
var b3 = document.createElement("input");
b3.type = "button";
b3.value = "Left";
//b1.onClick = func
activity.appendChild(b3);
var b4 = document.createElement("input");
b4.type = "button";
b4.value = "Right";
//b1.onClick = func
activity.appendChild(b4);
}
// when button is pressed, do createTable function
document.getElementById("gamesButton").addEventListener("click", createTable);
Using the brackets, you’re immediately invoking the startGame function. Its return value is then assigned to the onClick property.
You most likely want to assign the function itself, so it’s executed when the onClick event fires. To do so, change this
b1.onClick = startGame();
to this
b1.onClick = startGame;
I have this code that sends the values a user have typed in... the information and numbers are sent as an array and pushed into another array, I then display the text in a dynamically created list element and number in a span element...
var button = $('#add');
button.click(function()
{
var filmnamn = $('#name');
var filmnamnet = filmnamn.val();
var betyg = $('#star');
var betyget = betyg.val();
betyget = Number(betyget);
if(filmnamnet == 0)
{
$('#name').css('background-color', 'red');
}
if(betyget == 0)
{
$('#star').css('background-color', 'red');
}
if(betyget == 0 || filmnamnet == 0)
{
alert("Vänligen fyll i fälten korrekt");
}
else
{
var array = new Array();
array.unshift(betyget);
array.unshift(filmnamnet);
film_array.unshift(array);
betyg_array.unshift(array);
updateFilmList();
}
});
var film_list = $("#filmlista");
var film_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var filmen = film_array[0][0];
var grade = film_array[0][1];
var element = '<li class="lista">' + filmen + '<span class="betyg">'+ grade +'</span></li>';
film_list.append(element);
changeNumber();
}
And at last I have the function that i want to change the number in the span element to the amount of stars that the number shows... this works fine but only for the first created list and span element, when I try to add more listelements the number wont show up as stars, can someone tell me why this happens and point me in the direction to fix the problem?
function changeNumber(){
var elements= document.getElementsByClassName("betyg");
for (var i=0; i<elements.length; i++) {
var element = elements[i];
var length = parseInt(element.innerHTML);
var x=Array(length+1).join("*");
element.innerHTML=x;
}
}
I'm having trouble figuring out how to pass values from one function to another. I've created a program where I create boxes using values from a form that show up in the webpage. The values I'm talking about are property values of the boxes themselves.
Here is the function where the values are assigned to the boxes:
function addBox(newbox) {
for (var i = 0; i < newbox.number; i++) {
counter++;
var id = counter;
var scene = document.getElementById("scene");
var div = document.createElement("div");
div.value = id;
console.log(div.value);
div.className += " " + "box";
div.innerHTML += newbox.name;
div.style.backgroundColor = newbox.color;
var x = Math.floor(Math.random() * (scene.offsetWidth-101));
var y = Math.floor(Math.random() * (scene.offsetHeight-101));
div.style.left = x + "px";
div.style.top = y + "px";
scene.appendChild(div);
div.onclick = display;
}
}
Here is the function that I'm having trouble passing the values to. I need to pass them so that I can display them in an alert box when I click on each box:
function display(e) {
alert(e.target.toSource());
}
So far when I click it, I just get an empty pair of brackets in the alert box.
I tried your example in JS Fiddle: http://jsfiddle.net/jCC6n/
I'm seeing at least two problems.
"counter" is undefined, which causes the code to fail when it first attempt to increment it. I added a variable declaration at the top of the function.
toSource is undefined. I replaced that with "outerHTML", which works in Chrome, IE and presumably other browsers.
With the above changes, this worked.
function display(e) {
alert(e.target.outerHTML);
}
function addBox(newbox) {
var counter = 0;
for (var i = 0; i < newbox.number; i++) {
counter++;
var id = counter;
var scene = document.getElementById("scene");
var div = document.createElement("div");
div.value = id;
div.className += " " + "box";
div.innerHTML += newbox.name;
div.style.backgroundColor = newbox.color;
var x = Math.floor(Math.random() * (scene.offsetWidth-101));
var y = Math.floor(Math.random() * (scene.offsetHeight-101));
//div.style.left = x + "px";
//div.style.top = y + "px";
scene.appendChild(div);
div.onclick = display;
}
}
addBox({ number: 3, name: "Hello", color: '#C00' });
Be advised that event handling using onclick event handlers varies from browser to browser. It will be best to use a JavaScript framework that knows all the differences and gives you a unified way to handle events. jQuery is arguably the most used such framework.
I need to maintain text box values into an array in javascript onchange event. The text box control is created dynammically in javascript function. I have used below code. But at the end the array contains current element only. Previous values are not maintaining. How can I maintain textbox value each time entered.
<script type="text/javascript" language="javascript">
function DrawTextBox(j) {
var imgElement = document.getElementById('myimage');
var imgCoord = imgElement.getBoundingClientRect();
var cl = imgCoord.left + 20;
var x = x - cl;
var y = y - imgCoord.top;
var rect = document.getElementById(j);
if (rect == null) {
rect = document.createElement("div");
rect.id = j;
var pElement = document.getElementById("imgDiv");
pElement.appendChild(rect);
}
if (w < 0) {
w = 10;
}
if (h < 0) {
h = 10;
}
var l = parseInt(document.getElementById("hright").value) + 150 + 'px';
var style = rect.style;
// style.width = w + "px";
//style.height = h + "px";
style.left = l;
style.top = document.getElementById("htop").value;
style.backgroundColor = "Transparent";
//style.borderColor = "Blue";
style.position = "absolute";
style.borderStyle = "solid";
style.borderWidth = 2 + "px";
style.zIndex = 6000;
document.getElementById(j).innerHTML = "<textarea name=\"comments\" style=\" border:0\" Title=\"Enter Comment\" id=\"T1\" value=\"EnterComment:\" onchange=\"GetText()\" ></textarea>";
//document.getElementById(i).innerHTML = "<input type=\"Textarea\"...blah blah...></input>";
return rect;
}
function GetText() {
array1.push(document.getElementById('T1').value);
alert(array1.join(', '));
}
</script>
Your question doesn´t say if/when/where array1 is declared and when DrawTextBox() is called but you can´t insert multiple elements using the same ID "T1" as it violates basic HTML rules.
Try passing a referens to the current element like this onchange="GetText(this)" and use it in your GetText() function as;
function GetText(el) {
array1.push(el.value);
alert(array1.join(', '));
}