Why doesn't it work for rows 7-13 - javascript

The program is a Seat reservation program rows 1 and 2 are first class, row 3-9 are business class and rows 10 through 13 are economy. They are initialized to * and become X when it is reserved. and alert you if the seat is already filled.
The rows will fill for the first 6 rows but it ignores request for row 7 and beyond. But i know it goes to the appropriate function because if i request Economy with row 3 (which is invalid) it alerts me. But if i ask for first class with row7 it will act like nothing has been requested.
It won't let me post the html code but it will display as row1-13 on the left and A - F across the top. I use drop down list and I set the values to the corresponding for the options to their corresponding spot in a the 2-d array (eg if i select row 5 and seat c the value of row 5 is 5 and the value of C is 3)
var rowSeat;
function start()
{
rowSeat = new Array(14);
for(var i = 0; i <rowSeat.length; i++)
{
rowSeat[i] = new Array(7);
}
var j = 65;
for(var i = 1; i <rowSeat[0].length; i++)
{
rowSeat[0][i] = String.fromCharCode(j);
j++;
}
rowSeat[0][0] = " ";
for(var i = 1; i <rowSeat.length; i++)
{
rowSeat[i][0] = "Row "+i;
}
for(var i = 1; i <rowSeat.length; i++)
{
for(var j = 1; j <rowSeat[i].length; j++)
{
rowSeat[i][j] = "*";
}
}
display();
var subButton = document.getElementById("submitButton");
subButton.addEventListener("click", assign, false);
}
function display()
{
var results = "";
results+="<table>"
for(var i in rowSeat)
{
results+="<tr>";
for(var j in rowSeat[i])
{
results += "<td>" +rowSeat[i][j]+ "</td>";
}
results += "</tr>";
}
results+="</table>"
var show2 = document.getElementById( "show2" );
show2.innerHTML = results;
}
function assign()
{
var inputField = document.getElementById("classAssign");
var classType = inputField.options[inputField.selectedIndex].value;
if (classType == "FirstClass")
{
fClassSearch();
}
else if (classType == "Business")
{
bClassSearch();
}
else
{
eClassSearch();
}
display();
}
function fClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
var test = document.getElementById( "test" );
test.innerHTML = row +" "+ seat;
if (row >2){
var show2 = document.getElementById( "show" );
show.innerHTML = "Invalid choice only row 1 and 2 are First Class";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
function bClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
if (row <3 ||row >9){
var show2 = document.getElementById( "show" );
show.innerHTML = "Invalid choice only row 3 through 9 are BusinessClass";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
function eClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
var show1 = document.getElementById( "show" );
if (row <10){
show1.innerHTML = "Invalid choice only rows 10 through 13 are Economy Class";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
window.addEventListener("load",start, false);
</script>

var row = inputField.options[inputField2.selectedIndex].value;
inputField.options should be inputField2.options
inputField.options only goes to 6 because you only have 6 seats wide, but you are trying to look at the row in the seat list.

Related

how to add checkboxes in cells of first column of HTML table?

I am working on an app development which will read through my mailbox and list all the unread e-mails in a HTML table on my web-app upon click of a button. Below is the code which I have made while researching through google which solves for the purpose.
<!DOCTYPE html>
<html>
<body>
<button onclick="groupFunction()">Click me</button>
<table id="tblContents">
<tr onclick="tableClickTest()">
<th>Sender</th>
<th>Sent_Date</th>
<th>Received_By</th>
<th>Received_Date</th>
<th>Subject</th>
</tr>
</table>
<script>
function RowSelection()
{
var table = document.getElementById("tblContents");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
}
function tableText(tableCell) {
alert(tableCell.innerHTML);
}
function PopulateTable()
{
var objOutlook = new ActiveXObject("Outlook.Application");
var session = objOutlook.Session;
//alert(session.Folders.Count)
for(var folderCount = 1;folderCount <= session.Folders.Count; folderCount++)
{
var folder = session.Folders.Item(folderCount);
//alert(folder.Name)
if(folder.Name.indexOf("Premanshu.Basak#genpact.com")>=0)
{
for(var subFolCount = 1; subFolCount <= folder.Folders.Count; subFolCount++)
{
var sampleFolder = folder.Folders.Item(subFolCount);
//alert(sampleFolder.Name)
if(sampleFolder.Name.indexOf("test1")>=0)
{
for(var itmCount = 1; itmCount <= sampleFolder.Items.Count; itmCount++)
{
var itm = sampleFolder.Items.Item(itmCount);
if(!itm.UnRead)
continue;
var sentBy = itm.SenderName;
var sentDate = itm.SentOn;
var receivedBy = itm.ReceivedByName;
var receivedDate = itm.ReceivedTime;
var subject = itm.ConversationTopic;
// var contents = itm.Body;
var tbl = document.getElementById("tblContents");
if(tbl)
{
var tr = tbl.insertRow(tbl.rows.length);
// tr.onclick(tableClickTest())
if(tbl.rows.length%2 != 0)
tr.className = "alt";
var tdsentBy = tr.insertCell(0);
var tdsentDate = tr.insertCell(1);
var tdreceivedBy = tr.insertCell(2);
var tdreceivedDate = tr.insertCell(3);
var tdsubject = tr.insertCell(4);
// var tdcontents = tr.insertCell(5);
tdsentBy.innerHTML = sentBy;
tdsentDate.innerHTML = sentDate;
tdreceivedBy.innerHTML = receivedBy;
tdreceivedDate.innerHTML = receivedDate;
tdsubject.innerHTML = subject;
// tdcontents.innerHTML = contents;
}
//itm.UnRead = false;
}
break;
}
}
break;
}
}
return;
}
function groupFunction()
{
PopulateTable()
RowSelection()
}
</script>
</body>
</html>
The thing that I am now looking for and is unable to do is how do I add a checkbox in the first column in each row. Also upon checking this checkbox the entire row should get highlighted so that I can perform specific task on all the selected items.
As far as I have understood your code, your first column's data is being set as:
tdsentBy.innerHTML = sentBy;
So in the same line, you can add textbox as a string as:
var cbox = "<div class='select-box'>
<input type='checkbox' name='selectBox' class='select-row'>
</div?>"
tdsentBy.innerHTML = cbox + sentBy;
In this way, a checkbox will always be available in first column of every row.
Now in RowSelection function, to bind event you can do something like:
var checkBox = table.rows[i].cells[j].querySelector(".select-row");
checkBox.addEventListener("click",function(evt){
});

Issue with check, bet, or fold function in Poker game( javascript )

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.

javascript error - node was not found : replaceChild

I am trying to swap two array in javascript. While the replacement comes to the last iteration, I am getting "NotFoundError: Node was not found" in the call of parent.replaceChild(item2,item1). Please help me what mistake I have committed.
function sortTable(col){
if($("loacte-resultsTable") == null || $("loacte-resultsTable") == undefined){
return false;
}
if (lastSort == col) {
// sorting on same column twice = reverse sort order
absOrder ? absOrder = false : absOrder = true
}
else{
absOrder = true
}
lastSort = col;
try{
var loacteResultsTable = $("loacte-resultsTable").getElementsByTagName("TBODY")[0];
var loacteResultsTableTR = loacteResultsTable.getElementsByTagName("TR");
allTR = loacteResultsTableTR;
} catch (e) {
return false;
}
// allTR now holds all the rows in the dataTable
totalRows = allTR.length;
colToSort = new Array(); //holds all the cells in the column to sort
colArr = new Array(); //holds all the rows that correspond to the sort cell
copyArr = new Array(); //holds an original copy of the sort data to match to colArr
resultArr = new Array(); //holds the output
allNums = true
allDates = true
//store the original data
//remember that the first row - [0] - has column headings
//so start with the second row - [1]
//and load the contents of the cell into the array that will be sorted
for (x=0; x < totalRows; x++){
var data = setDataType(allTR[x].childNodes[col].innerText);
if(typeof data!="undefined"){
colToSort[x] = setDataType(allTR[x].childNodes[col].innerText);
}else{
colToSort[x] = setDataType(allTR[x].childNodes[col].textContent);
}
colArr[x] = allTR[x];
}
//make a copy of the original
for (x=0; x<colToSort.length; x++){
copyArr[x] = colToSort[x];
}
//sort the original data based on data type
if (allNums){
colToSort.sort(numberOrder);
} else if (allDates){
colToSort.sort(dateOrder);
} else {
colToSort.sort(textOrder);
}
//match copy to sorted
for(x=0; x<colToSort.length; x++) {
for(y=0; y<copyArr.length; y++) {
if (colToSort[x] == copyArr[y]) {
boolListed = false
//search the ouput array to make sure not to use duplicate rows
for(z=0; z<resultArr.length; z++) {
if (resultArr[z]==y) {
boolListed = true
break;
}
}
if (!boolListed){
resultArr[x] = y
break;
}
}
}
}
//now display the results - it is as simple as swapping rows
for (x=0; x<resultArr.length; x++) {
//allTR[x].swapNode(colArr[resultArr[x]])
swapNodes(allTR[x],colArr[resultArr[x]]);
}
function swapNodes(item1,item2)
{
var itemtmp = item1.cloneNode(1);
var parent = item1.parentNode;
item2 = parent.replaceChild(itemtmp,item2);
parent.replaceChild(item2,item1);
parent.replaceChild(item1,itemtmp);
itemtmp = null;
}
}
The call to the sortTable method is from synch().This is the UI part coded in JS:
function synch(){
var loacteResults = $('loacte-results');
var loacteResultsTable = $('loacte-resultsTable');
tab = loacteResults.getElementsByTagName('TABLE')[0];
loacteResults.removeChild(tab);
var updatedResults =
'<table id="loacte-resultsTable" cellspacing="0" cellpadding="3" border="1">' +
'<thead class="thead">' +
'<tr>' +
'<th>Site ID</th>' +
'<th>Store Name</th>' +
'<th>Agent Code</th>' +
'<th>Address</th>' +
'<th>City, State</th>' +
'<th>Phone</th>' +
'<th>Hours</th>' +
'<th>Deleted</th>' +
'<th width="65px;">Priority <img src="images/sort_up_down.gif" onclick="javascript:sortTable(8)" style="cursor: pointer;"/></th>' +
'<th width="115px;">Est.Dist.(miles) <img src="images/sort_up_down.gif" onclick="javascript:sortTable(9)" style="cursor: pointer;"/></th>' +
'</tr>' +
'</thead>' ;
if(tr == '')
updatedResults = updatedResults + '<tbody><tr><td colspan="10">No Stores to display</td></tr></tbody></table>';
else
updatedResults = updatedResults + '<tbody>' + tr + '</tbody></table>';
loacteResults.innerHTML = updatedResults;
}
In the third parent.replaceChild line item1 is no longer is on the page, since it has been replaced with item2.
Your code broken down:
function swapNodes(item1,item2)
{
var itemtmp = item1.cloneNode(1); //create a copy of item 1
var parent = item1.parentNode; //set a reference to the parent
item2 = parent.replaceChild(itemtmp,item2); //replace item2 with the copy of item1 and store the old child in item2
parent.replaceChild(item2,item1); //replace item1 with item2
parent.replaceChild(item1,itemtmp); //this line is redundant. <-- item1 no longer is on the page.
itemtmp = null;
}

How to check value of table td?

I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name

change numbers from dynamic elements

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;
}
}

Categories