Here I'm developing snakes and ladder game.
First I have developed game board and placed numbers on that, but I don't know how to put snakes and ladder on some positions.
Could anybody guide me please?
function loadgameboard() {
var numbers = 64;
var tablestart = "<table id='contentTable' width='35%' background='' height='74%' bgcolor='#EFE8BB' border=1>";
var tableend = "</table>";
var trstart = "<tr>";
var trend = "</tr>";
var tdstart = "<td align='middle' >";
var tdend = "</td>";
var fontsizeStart = "<font size='5'>";
var fontSizeEnd = "</font>";
var numberOfRowColumns = Math.sqrt(numbers);
document.write(tablestart);
for (var i = numberOfRowColumns; i > 0; i--) {
document.write(trstart);
for (var j = numberOfRowColumns; j > 0; j--) {
document.write(tdstart);
document.write(fontsizeStart);
document.write(numbers);
document.write(fontSizeEnd);
document.write(tdend);
numbers--;
}
document.write(trend);
}
document.write(tableend);
}
window.onload = loadgameboard;
Suppose if I want to place one snake and one image, how can I do it?
Your help will be appreciated.
Your tdstart variable should include an id field, such as: var tdstart = "<td align='middle' id="; Don't set the id here, or close the tag yet. In the loop where you create the table, do something like this: document.write(tdstart+ "'"+i+j+"'>"); That gives every data-cell a unique ID and also closes the tag. After that, at any time you like, you can set some other variable, perhaps one named tcell to any of the cells in the table: tcell=document.getElementById('15'); where the 15 specifies a row and a column; if you have more than 10 of each, you might use letters of the alphabet instead of digits--just remember to assign letters instead of numbers i and j to the id= part of your main loop. That could be done by
document.write(tdstart+ "'"+"ABCDEFGHIJKLMNOP".substr(i,1)+"ABCDEFGHIJKLMNOP".substr(j,1)+"'>");
Use more letters as needed, and remember lowercase is different from uppercase, you can handle a 52x52 table this way.
Once you have access to the cell, you can edit its content, such as
tcell.innerHTML="64"+"<img src='ladder.png' />"
The 64 is the original number you put in the cell, in your loop. You can change the number, or put it after the image, or both. And of course you can remove the image: tcell.innerHTML="64";
Related
I'm currently in a JavaScript course that is asking me to have the following happen:
User enters names one at a time into a form, then presses Submit
The names are stored into an array and output to a table
As names are entered (and added to the table), a total must update as well--based on the array, not just from counting table elements
My current issue is I'll add one name, then the total shows "1"--when I add a second name, the total displays "11"
This is currently what my JavaScript code looks like:
function displayNamesAndTotal() {
// Your code goes in here.
var userInputName = [];
var totalNamesEntered = [];
var countTotal = 0;
var firstName;
var arrayIndex;
var output;
var outputTotal;
var form;
form = document.getElementById("userFormId");
output = document.getElementById("userEntriesId");
outputTotal = document.getElementById("testId");
//userInputName[0] = form.firstname.value;
userInputName.push(form.firstname.value)
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
output.innerHTML += "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
countTotal += userInputName.length;
}
outputTotal.innerHTML += countTotal;
return false;
}
I've spent the past day or so trying to figure out what I'm doing wrong--and it's probably something embarrassingly easy--but I'm at a loss and could use guidance
Any suggestions?
Thanks
It looks like your total is storing a string instead of a number. Try using parseInt(number) to convert the string into a number.
Good grief, from reading the other answers from you guys I think I have it licked
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
tableData = "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
totalCount = userInputName.length;
}
output.innerHTML += tableData;
outputTotal.innerHTML = "<h4>Total Number of Strings: " + totalCount + "</h4>";
form.string.select();
return false;
This way the totalCount acted as the array's length when it went through the loop, then outside in the innerHTML statement I could display it and have it constantly update whenever a new string was submitted.
Thank you for all of your feedback
outputTotal.innerHTML is a string, so adding to it would concatenate the strings together. Since outputTotal.innerHTML starts out as null, add 1 to it creates "1". When you add 1 to it again, outputTotal.innterHTML is already "1", so it becomes "11".
Instead of incrementing outputTotal.innerHTML try setting the HTML to it directly.
outputTotal.innerHTML = countTotal;
I have made an array with objects that get there info from three different user variables, however on one of these there are many sub variables that i don't want it to repeat itself every time the user presses the select button(which updates the table) instead i want it to just add onto (or take away) from the sections that it already has in the table. thanks(if you need the variable code let me know) I have been trying to solve thi for a while now! please help!!
//creating array
var gProducts = new Array();
var gTotalCost = 0;
// Adding Products to array gProducts
function addProduct
{
var product = new Object();
product.name = name;
product.cost = cost;
gProducts.push(product);
gTotalCost += parseInt(cost)
}
//Getting products from array, use of for in loop setting new table rows in blank var for each array item
function renderProducts()
{
var HTMLadd = ""
for (var i in gProducts)
{
if( gProducts[i].cost > 0){
HTMLadd = HTMLadd +
"<tr>"+
"<td class='tableSettings00' id=tableRow2 >" + gProducts[i].name +
"</td>"+
"<td class='tableSettings'>€<span id=tableRow2part2>" + gProducts[i].cost +
"</span></td>"+
"</tr>";
}
else
{
}
}
document.getElementById('tableRow').innerHTML = HTMLadd;
}
You're using a for in loop, when you probably wanted just a for loop.
Change this line to
for (var i in gProducts)
to
for (var i = 0; i < gProducts.length; i++)
With a for/in loop, the variable i will be an object, and not an integer.
I have a problem I am not able to fix, quite difficult to explain but I will do my best.
Basically I have created a web application (in CodeIgniter) that takes some data of an array coming from a json encoding and adds rows to a table by using the jQuery .prependTo() method in the success function.
Every row of the table contains different elements from the database (coming from the json), depending from the value of the i counter.
The code is as the following (i cut the part about the <tr> and <td> content, it's just styling)
$.ajax({
type: "get",
async: false,
....
....
success: function(data) {
var i;
var item_cost = new Array();
var item_name = new Array();
var item_code = new Array();
var item_interno = new Array();
for(i = 0; i < data.length; i++) {
item_cost[i] = data[i].cost;
item_name[i] = data[i].name;
item_code[i] = data[i].code;
item_interno[i] = data[i].codiceinterno;
var newTr = // creates the <tr>
newTr.html('//creates the <td>')
newTr.prependTo("#myTable");
}
},
I am sorry if it is a bit unclear, if you need me to update the code because I missed something important let me know and I will do it, but this code alone should explain my problem.
The application works beautifully if in the database there are just a little number of rows (for example, i = 300). They are showed and rendered correctly and I don't get any browser slowing process. But when I work with i = 4000 rows, the browser starts acting slow just like the Javascript code is too heavy to render, and i get "lag" while trying to scroll down the html table, or inputting some values in the input boxes inside the table (to later update it by clicking a button). This is my problem: I am quite sure I'm doing something wrong that is loading up too much memory, as I tested this also on very strong computers. Even totally disabling my CSS won't do the trick.
Thanks for any help you can give me, it would be really appreciated.
The problem
You are using a lot of function call inside a loop. That take a lot of juice and the more item you have, the slower it is.
To solve that, we need to reduce the number of function calls.
My suggestion
Working with native JavaScript would save on performance here. So I suggestion you use string concatenation instead of DOM manipulation methods of jQuery.
Let rework you loop. Since you want your data in a descendant order, we need to reverse the loop :
for(i = data.length; i >= 0; i--)
Then simple string concatenation to build a tr. For that you need a var outside the loop:
var myHTML = ''; //That's the one!
var i;
var item_cost = new Array();
var item_name = new Array();
var item_code = new Array();
var item_interno = new Array();
And build the tr with +=. Although, using a single line would make it faster, but less readable :
for(i = data.length; i >= 0; i--) {
item_cost[i] = data[i].cost;
item_name[i] = data[i].name;
item_code[i] = data[i].code;
item_interno[i] = data[i].codiceinterno;
myHTML += '<tr>';
myHTML += '<td>'+yourData+'</td>';//add those data here
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '</tr>';
}
Then, prepend it to your table :
var myHTML = '';
var i;
var item_cost = new Array();
var item_name = new Array();
var item_code = new Array();
var item_interno = new Array();
for(i = data.length; i >= 0; i--) {
item_cost[i] = data[i].cost;
item_name[i] = data[i].name;
item_code[i] = data[i].code;
item_interno[i] = data[i].codiceinterno;
myHTML += '<tr>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '</tr>';
}
$('#myTable').prepend(myHTML);
Limitation
From my test, the string length can be 2^28 but cannot be 2^29. That make a maximum length of approx. 268,435,456 (approx. might not be the best word here since it's between 268,435,456 and 536,870,912.
If you data character count is higher than that (but let be honnest, that would be a lot of data), you might have to split you string into 2 variables.
I know this is not a real answer to your question, but...
jQuery definitely causes the lag - no wonder. But - whether you choose jQuery to build the table or you just concatenate HTML - let's agree on that: 4000 rows is definitely a lot of data. Too much data? I would say: 200 already is. If we go thousands, the question pops up: why? Is there any application-related reason you really need to retrieve such a big number of records at once? Some of them will probably never be read.
Why not try an ajax-based lazy load approach? Loading 50-record portions every time would seem more robust IMO, and would definitely be a better UX.
My two cents: Why don't retrieve the rows composed from the server instead of making the client work to compound it? You could even cache it. The only thing would be that you'll have more traffic, but in the browser it'll go smoother
UPDATE
To achieve it, you can make your method to distinguish between ajax input or not, and show only $tbody, or the whole table according to it. It would be something like:
$tbody = $this->load->view( 'view_with_oly_tbody', $data, true );
if ( $this->input->is_ajax_request() ) {
return $tbody;
} else {
$data['tbody'] = $tbody;
$this->load->view('your_view_with_table_with_tbody_as_var', $data);
}
Note: Code above will vary according to your views, controller, if you have json in your AJAX or not, write the return in other part, etc. Code above is just for clarify my point with CI.
Ah! and you'll have to manage the answer in the client to append/prepend/substitute the body of the table.
I am attempting to print out lables (bar codes) from a table using JS (the table is using JQ Tablesorter) and the barcode jquery. My issue is that I need to iterate through all of the isbn's and it is showing one number per line. Here is the code I have:
$("#barcode").live('click', function(){
var title="";
var isbn="";
var first = "";
var second = "";
var indexGlobal = 0;
$('#acctRecords tbody tr').each(function()
{
isbn += $(this).find('#tableISBN').html();
title += $(this).find('#tableTitle').html();
}); //end of acctRecords tbody function
//Print the bar codes
var x=0;
for (x=0;x<isbn.length;x++)
{
first += '$("#'+indexGlobal+'").barcode("'+isbn[x]+'", "codabar",{barHeight:40, fontSize:30, output:"bmp"});';
second += '<div class="wrapper"><div id="'+indexGlobal+'"></div><div class="fullSKU">      '+isbn[x]+
'</div><br/><div class="title">'+title[x]+'</div></div><br/><br/>';
indexGlobal++;
}
var barcode = window.open('','BarcodeWindow','width=400');
var html = '<html><head><title>Barcode</title><style type="text/css">'+
'.page-break{display:block; page-break-before:always; }'+
'body{width: 8.25in;-moz-column-count:2; -webkit-column-count:2;column-count:2;}'+
'.wrapper{height: 2.5in;margin-left:10px;margin-top:5px;margin-right:5px;}'+
'.fullSKU{float: left;}'+
'.shortSKU{float: right;font-size:25px;font-weight:bold;}'+
'.title{float: left;}'+
'</style><script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js"></script><script type="text/javascript" src="../barcode/jquery-barcode.js"></script><script>$(document).ready(function() {'+first+'window.print();window.close();});</script></head><body>'+second+'</body></html>';
barcode.document.open();
barcode.document.write(html);
barcode.document.close();
}); // end of click function
I am pretty sure that the issue is with these lines:
var x=0;
for (x=0;x<isbn.length;x++)
For example if an isbn is 9780596515898 I am getting 9 on the first line, 7 on the second, 8 on the third etc.
How do I get it to print out the entire isbn on one line?
Nope, those 2 lines are fine. But these 2, on the other hand...
var isbn="";
...
isbn += $(this).find('#tableISBN').html();
This makes isbn a string. And you are just making the string longer every time you add an isbn to it. "string".length will tell you the number of characters in that string, which is why you get one character per iteration.
You want an array instead, which you append items to with the [].push() method. [].length will tell you the number of items in that array.
var isbn = [];
...
isbn.push($(this).find('#tableISBN').html());
for (var x=0; x<isbn.length; x++) {
isbn[x]; // one isbn
}
I'm having some trouble getting my code to work. This is what I have so far.
function outputNamesAndTotal() {
var name;
var outputTable;
var inputForm;
var nameArray;
var outputDiv;
outputDiv = document.getElementById("outputDiv");
inputForm = document.getElementById("inputForm");
outputTable = document.getElementById("outputTable");
name = inputForm.name.value;
nameArray = [];
nameArray.push(name);
for (var i = 0; i > nameArray.length; i++) {
outputTable.innerHTML += "<tr>" + nameArray[i] + "</tr>";
}
inputForm.name.focus();
inputForm.name.select();
return false;
}
When I add the loop it breaks the code completely, but I can't figure out why.
What I'm trying to do is use an HTML form to get a name from the user. Once the user enters the name, the program adds the name to the array, and outputs each array entry to a row in a table.
It's pretty basic, but it's still giving me all kinds of trouble!
I think you are clearing your array of names every time you call the function. You should bring the line:
nameArray = [];
out and make it global.
I ran a quick test and the following code works in at least FireFox
Edited to use appendChild
<html>
<head>
<script type='text/javascript'>
var names = [];
function addName() {
var nameTxt = document.getElementById('name_txt');
var name = nameTxt.value;
names.push(name);
var outTable = document.getElementById('out_tbl');
var row = document.createElement('tr');
var entry = document.createElement('td');
var txt = document.createTextNode(name);
entry.appendChild(txt);
row.appendChild(entry);
outTable.appendChild(row);
var numDiv = document.getElementById('num_div');
removeAllChildren(numDiv);
var numTxt = document.createTextNode('You have ' + names.length + ' names');
numDiv.appendChild(numTxt);
}
function removeAllChildren(e) {
while (e.hasChildNodes()) {
e.removeChild(e.firstChild);
}
}
</script>
</head>
<body>
<table id='out_tbl'>
</table>
<div id='num_div'>You have 0 names</div>
<input id='name_txt' type='text'/>
<button onclick="addName()">CLICK</button>
</body>
</html>
Edit: Oh yeah and you are the fact that you are looping through the array every time. If you "globalize" the name array, you're gonna print the whole array every time you add a name.
Edit x2: the code you originally posted had nameArray as a local variable inside the function. This effectively clears the array every time you call the function. Then every time you call the function you add the current name to the now empty array, and loop through all 1 (one) elements that the array now holds.
What you want to do is "globalize" the name array, and remove the loop from your function. This will allow you to build up your name array across multiple calls, and works the way that you want it.
Also, innerHTML is not really the best way to add things to the page. I would suggest using appendChild().
-C
for (var i = 0; i > nameArray.length; i++) {
I think you mean i < nameArray.length