I want to create a button that produces a 3x3 HTML table meant for a card game, where each cell corresponds to one single image. For the time being, I'm mainly focusing on filling individual cells with a card number taken from an array element, using a step-by-step rationale. This is what the final result should look like in HTML, derived from the produced script;
<table style="width:100%">
<tr>
<td><img src="1.png"></td>
<td><img src="2.png"></td>
<td><img src="3.png"></td>
</tr>
<tr>
<td><img src="4.png"></td>
<td><img src="5.png"></td>
<td><img src="6.png"></td>
</tr>
<tr>
<td><img src="7.png"></td>
<td><img src="8.png"></td>
<td><img src="9.png"></td>
</tr>
</table>
This is what I'm currently working at, although with not much success
<!DOCTYPE html>
<html>
<body>
<table id="1">
</table>
<button onclick="createTable()">Create</button>
<script>
function createTable() {
var deck = [1,2,3,4,5,6,7,8,9];
function shuffle(o) { //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
shuffle(deck);
document.getElementById("1").innerHTML = "<tr><td>" + deck[0] + "</td><td>" + deck[1] + "</td><td>" + deck[2] + "</td></tr>" +
"<tr><td>" + deck[3] + "</td><td>" + deck[4] + "</td><td>" + deck[5] + "</td></tr>" +
"<tr><td>" + deck[6] + "</td><td>" + deck[7] + "</td><td>" + deck[8] + "</td></tr>" +
;
}
</script>
</body>
</html>
Note
The 9-card deck is shuffled using a pretty basic and self-explanatory function.
Edit. My final version, which is returning broken image.
<!DOCTYPE html>
<html>
<body>
<table id="1">
</table>
<button onclick="createTable()">Create</button>
<script>
function createTable() {
var deck = [1,2,3,4,5,6,7,8,9];
function shuffle(o) {
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
shuffle(deck);
document.getElementById("1").innerHTML = "<tr><td><img src=" + deck[0] + ".png'></td><td>" + deck[1] + "</td><td>" + deck[2] + "</td></tr>" +
"<tr><td>" + deck[3] + "</td><td>" + deck[4] + "</td><td>" + deck[5] + "</td></tr>" +
"<tr><td>" + deck[6] + "</td><td>" + deck[7] + "</td><td>" + deck[8] + "</td></tr>"
;
}
</script>
</body>
</html>
After you fix your code by removing the extra + at the last line where you build your html (tr's and td's), you will simply need just to replace
"<td>" + deck[0] + "</td>"
by
"<td><img src='" + deck[0] + ".png'></td>"
... and so on for other indexes like deck[1], deck[2] etc.
You have got an extra "+"
document.getElementById("1").innerHTML = "<tr><td>" + deck[0] + "</td><td>" + deck[1] + "</td><td>" + deck[2] + "</td></tr>" +
"<tr><td>" + deck[3] + "</td><td>" + deck[4] + "</td><td>" + deck[5] + "</td></tr>" +
"<tr><td>" + deck[6] + "</td><td>" + deck[7] + "</td><td>" + deck[8] + "</td></tr>";
Should work better.
Your shuffle() is pretty convoluted. Let me advise you to write less exotic code. Making your code more readable will help to find potential errors. Indeed, the problem is not so hard to locate actually: https://stackoverflow.com/a/34471591/1636522 :-)
var deck = [1, 2, 3, 4, 5, 6, 7, 8, 9];
document.write(JSON.stringify(shuffle(deck), 0, 1));
function shuffle (anArray) {
var i, j, x, l = anArray.length;
for (i = 0; i < l; i++) {
j = rdmInt(l);
x = anArray[i];
anArray[i] = anArray[j];
anArray[j] = x;
}
return anArray;
}
function rdmInt (max) {
return Math.floor(Math.random() * max);
}
The same remark applies to your string concatenation:
document.getElementById("1").innerHTML = ""
+ "<tr>"
+ "<td><img src=" + deck[0] + ".png'></td>"
+ "<td>" + deck[1] + "</td>"
+ "<td>" + deck[2] + "</td>"
+ "</tr>"
+ "<tr>"
+ "<td>" + deck[3] + "</td>"
+ "<td>" + deck[4] + "</td>"
+ "<td>" + deck[5] + "</td>"
+ "</tr>"
+ "<tr>"
+ "<td>" + deck[6] + "</td>"
+ "<td>" + deck[7] + "</td>"
+ "<td>" + deck[8] + "</td>"
+ "</tr>";
Can you see the error now (line 3)? Here is a fix:
+ "<td><img src=\"" + deck[0] + ".png\"></td>"
You could go even further to avoid repetitions (dry):
var deck = [
"KNhxd", "7CtbR", "Os8qX",
"21SKd", "CWMZC", "43C1X",
"lpGvK", "8Wk7W", "Y3JFi"
];
// preserve the global namespace with an IIFE
document.body.innerHTML = function () {
var ROOT = "http://i.stack.imgur.com/";
function toTable (deck) {
var i, html = "";
for (i = 0; i < 3; i++) {
html += toTr(deck.slice(i * 3, (i + 1) * 3));
}
return "<table>" + html + "</table>";
}
function toTr (row) {
return "<tr>" + row.map(toTd).join('') + "</tr>";
}
function toTd (cell) {
return "<td><img src=\"" + ROOT + cell + ".png\" /></td>";
}
return toTable(deck);
}();
body{background:#006600;}
img{display:block;width:35px;}
If you want to create HTML elements, then you do not just write them as a text string and insert into an existing HTML element.
You create an element node (and text node if applicable) and append that to your existing HTML element.
Here is an article on w3 schools about creatung HTML tags with JavaScript.
http://www.w3schools.com/jsref/met_document_createelement.asp
If your table is always 9 cells then why not just write the HTML out giving each cell a unique id. Then u could use code similar to what u have.
document.getElementById("cell_1").innerHTML = deck[0];
You would need to include this logic for all 9 cells / values, although you could loop through them like;
for (i = 0; i < 8; i++) {
var cellNo = i + 1;
document.getElementById("cell_" + cellNo).innerHTML = deck[i];
}
Hope this helps ;)
In addition to the unnecessary '+' at the end of your innerHTML addition,
I would suggest making your code more flexible. Instead of adding the data hardcoded to your innerHTML you can do something like this:
var endOfRowCounter = 0;
var toAppend = "";
deck.forEach(function(card){
if(endOfRowCounter % 3 == 0) {
toAppend += "<tr>";
}
toAppend += "<td><img src=\"" + card + ".png\"></td>";
if(endOfRowCounter % 3 == 2)
{
toAppend += "</tr>";
}
endOfRowCounter++;
});
When I load your code I get this message in the browser console:
Uncaught SyntaxError: Unexpected token ;
It might help if you update this code:
document.getElementById("1").innerHTML = "<tr><td>" + deck[0] + "</td><td>" + deck[1] + "</td><td>" + deck[2] + "</td></tr>" +
"<tr><td>" + deck[3] + "</td><td>" + deck[4] + "</td><td>" + deck[5] + "</td></tr>" +
"<tr><td>" + deck[6] + "</td><td>" + deck[7] + "</td><td>" + deck[8] + "</td></tr>" +
;
To this:
document.getElementById("1").innerHTML = "<tr><td>" + deck[0] + "</td><td>" + deck[1] + "</td><td>" + deck[2] + "</td></tr>" +
"<tr><td>" + deck[3] + "</td><td>" + deck[4] + "</td><td>" + deck[5] + "</td></tr>" +
"<tr><td>" + deck[6] + "</td><td>" + deck[7] + "</td><td>" + deck[8] + "</td></tr>";
To loop your array and create your table structure with the images, you could do this for example:
function createTable() {
var deck = [1,2,3,4,5,6,7,8,9];
function shuffle(o) { //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
shuffle(deck);
var html = '';
for (var i = 0; i < deck.length; i++) {
if (i%3 === 0) {
html += "<tr>";
}
html += '<td><img src="' + deck[i] + '.png"></td>';
if (i%3 === 2) {
html += "</tr>";
}
}
document.getElementById("1").innerHTML = html;
}
Related
I am using json.data.schedules[0].liveVideoList , json.data.schedules[1].liveVideoList
, json.data.schedules[2].liveVideoList and so on
Please tell me how can I use loop here to get all path
script.js code
var b = location.search.split('b=')[1];
$.get(
"index2.php",
{ "b": b },
function (data) {
var json = JSON.parse(data);
$.each(json.data.schedules[0].liveVideoList, function (i, v) {
var str = v.thumbnailUrl.split("vi/").pop();
var datee = v.publishDate.slice(0, 9);
var timee = v.publishDate.slice(9, 20);
var tblRows = "<tr>" + "<td>" + v.title + "</td>" + "<td>" + 0 + ' ₹' + "</td>" + "<td>" + datee + "</td>" + "<td>" + timee + "</td>" + "<td><a target='_blank' href='" + str + "'>" + "WATCH/DOWNLOAD" + "</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata");
});
}
);
You can use two loops like this.
$.each(json.data.schedules, function (index, schedule) {
$.each(schedule.liveVideoList, function (i, v) {
var str = v.thumbnailUrl.split("vi/").pop();
var datee = v.publishDate.slice(0, 9);
var timee = v.publishDate.slice(9, 20);
var tblRows = "<tr>" + "<td>" + v.title + "</td>" + "<td>" + 0 + ' ₹' + "</td>" + "<td>" + datee + "</td>" + "<td>" + timee + "</td>" + "<td><a target='_blank' href='" + str + "'>" + "WATCH/DOWNLOAD" + "</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata");
});
});
A for..of loop
for (let schedule of json.data.schedules) {
//Do something with schedule
}
A for..in loop
for (let scheduleIndex in json.data.schedules) {
//Do something with json.data.schedules[scheduleIndex]
}
A for loop
for (let index = 0; index < json.data.schedules.length; index++) {
//Do something with json.data.schedules[index]
}
A while loop
var index = 0;
while (index < json.data.schedules.length) {
//Do something with json.data.schedules[index]
index++;
}
I Know why I'm getting undefined but i have no idea how to solve.
Tried to put null, but it is taking in as a text
var text ='{"employees":[' +
'{"name":"Tony","mobile":"99221111","email":"tony#json.com"},' +
'{"name":"Linda","mobile":"98981111","email":"linda#json.com"},' +
'{"name":"Patrick","mobile":"90902222","email":"patrick#json.com"},' +
'{"name":"Isabella","mobile":"99552222"}]}';
obj = JSON.parse(text);
for(var i in obj.employees)
{
document.getElementById("table").innerHTML += "<tr><td>" + obj.employees[i].name + "</td>" + "<td>" + obj.employees[i].mobile + "</td>"
+ "<td>" + obj.employees[i].email + "</td></tr>";
}
Hi, for Isabella there is no email, hence I'm getting undefined when I loop through to print out their details on html, however what I'm expecting is for the email portion to be empty in the table for Isabella. Is there a way to solve it?
You can use logical OR (|| in JavaScript), which will use the second value (empty string in this case) if the first value (email) is undefined:
var text = '{"employees":[' +
'{"name":"Tony","mobile":"99221111","email":"tony#json.com"},' +
'{"name":"Linda","mobile":"98981111","email":"linda#json.com"},' +
'{"name":"Patrick","mobile":"90902222","email":"patrick#json.com"},' +
'{"name":"Isabella","mobile":"99552222"}]}';
obj = JSON.parse(text);
for (var i in obj.employees) {
document.getElementById("table").innerHTML += "<tr><td>" + obj.employees[i].name + "</td>" + "<td>" + obj.employees[i].mobile + "</td>" +
"<td>" + (obj.employees[i].email || '') + "</td></tr>";
}
<table id="table"></table>
Having a few issues trying to get this function output to an ajax table (working fine) and an input box called connectsList1.
i cannot get it to spit out into the input box without error, the error is
Uncaught TypeError: Cannot set property 'innerHTML' of null
and
connectsList1 is not defined
function getConnections(txt1) {
func_getConnections(
function (response) {
var sortorder = txt1;
var arr = response;
var i;
var Count;
var mCount;
var oCount;
var out =
"<thead>"
for (i = 0; i < arr.length; i++) {
out +=
"<tr>" +
"<tbody>" +
"<tr class=\"" + ReturnValuesAsColor(arr[i].o, arr[i].m, arr[i].server_proc) + "\">" +
"<td>" + arr[i].id + "</td>" +
//"<td>" + arr[i].user_id + "</td>" +
"<td>" + arr[i].user_name + "</td>" +
"<td>" + arr[i].workstation_name + "</td>" +
"<td>" + (!!arr[i].ip_address ? arr[i].ip_address : '') + "</td>" +
"<td>" + formatDateTime(arr[i].connect_date, 'datelongtime') + "</td>" +
"<td>" + formatDateTime(arr[i].refresh_date, 'datelongtime') + "</td>" +
"<td>" + (!!arr[i].app_ver ? arr[i].app_ver : '') + "</td>" +
"<td>" + (!!arr[i].app_date ? formatDateTime(arr[i].app_date, 'shortdate') : '') + "</td>" +
"<td>" + Messages_flag(arr[i].get_messages_flag) + "</td>" +
"<td>" + FixNumbers(arr[i].message_type_flags) + "</td>" +
//"<td>" + arr[i].o + "</td>" +
//"<td>" + arr[i].m + "</td>" +
"<td>" + arr[i].group_name + "</td>" +
//"<td>" + arr[i].server_proc + "</td>" +
"<td> <button id=\"DelImg1\" type=\"button\" name=\"btnsubmit\" class=\"ui-button ui-widget ui-state-default ui-corner-all\" onclick=\"clearText('<%= result.ClientID%>'); CopyId(" + arr[i].id + "); return Message(" + arr[i].id + ")\" >Delete</button> </td>" +
"</tr>" +
"</tbody>";
mCount = 0
if (arr[i].m != 0) {
mCount += 1;
} else if (arr[i].o != 0) {
oCount += +1;
} else if (arr[i].o == 0 & arr[i].m == 0) {
Count += 1;
}
document.getElementById("dtBody1").innerHTML = out;
document.getElementById('ConnectsList1').innerHTML = out;
ConnectsList1 = " Connection list: " & Count + oCount + mCount & " connection(s) Main Application : " & Count & " Online : " & oCount & " Mobile : " & mCount;
}})};
Any help or advice welcome, still learning ajax myself
document.getElementById("dtBody1") can not find any tag with id dtBody1. Make sure your HTML has an element with that ID.
And remember to declare the ConnectsList1 variable to avoid the second error.
Fiddle
I want to put the names of all record in my array into a table my array isn't index correctly so i used $.each instead of iterating over the using for loop. My problem is I only get to show the last element but if i try to show a value that is existing to both the array it is showing correctly.
What am i missing in this code.
Any idea is appreciated
This is my javascript
for (var i = 0; i < name.length; i++) {
var names = name[i].Names;
$.each(names, function (item, names) {
tr = $('<tr class=""/>');
//console.log(complainant[obj]);
//var names = complainant[obj];
//if(names.hasOwnProperty('fname')){
console.log(names.suffix);
var acronymc;
var upper = names.mname.toUpperCase();
if (upper) {
var matches = upper.match(/\b(\w)/g);
//var matches = upper.replace(/^(\S+)\s+(\S).*/, '$1 $2.');
//acronym = upper.slice(0,1);
var acronym1 = matches.join('');
acronymc = acronym1.slice(-1);
} else {
acronymc = '';
}
tr.append("<td id=''>" + "<span id='fname'>" + names.fname + "</span>" + " " + "<span id='mname'>" + acronymc + "</span>" + " " + "<span id='lname'>" + names.lname + "</span>" + " " + "<span id='suffix'>" + names.suffix + "</span>" + "</td>");
tr.append("<td id=''>" + '<span id="street">' + names.street + '</span>' + " " + '<span id="brgy">' + names.brgy + '</span>' + " " + '<span id="town">' + names.town + '</span>' + " " + '<span id="city">' + names.city + '</span>' + "</td>");
tr.append("<td id=''>" + names.contactnum + "</td>");
tr.append("<td id=''>" + "<a href='#' class='editcomplainant'>Edit</a>" + "/" + "<a href='#' class='delete'>Delete</a>" + "</td>");
//}
});
$("#nameslist").append(tr);
}
Put the $('#nameslist').append(tr); call inside the $.each block.
Here is a way of improving the creation of tds:
var html =
"<td>" +
"<span id='fname'/> " +
"<span id='mname'/> " +
"<span id='lname'/> " +
"<span id='suffix'/>" +
"</td>";
var td = $(html);
td.find('#fname').text(names.fname);
td.find('#mname').text(acronymc);
td.find('#lname').text(names.lname);
td.find('#suffix').text(names.suffix);
tr.apppend(td);
Why is this better (imho)?
You will not create unintentional html tags by having < and > inside the variables.
Appropriate escaping (auml codes) will be automatically generated
It is easier to read
first of all i need to say that i don't have much experience with JS. currently i'm trying to implement an web application with MVC framework. I'm in a work to develop an app that is also compatible with Internet explorer. in that case i'm using following JS method to populate a table which is working fine with all the browsers....
function populateTable(array) {
document.getElementById("instalationTable").style.display = "block";
var table = document.getElementById("ActivityDescription_installationID");
table.innerHTML = "";
elementsInTable = array;
var x = 0;
for (i = 0; i < (array.length * 2) ; i++) {
//alert(i);
if ((i % 2) == 0) {
//ID Row
var row = table.insertRow(i);
var cell_1 = row.insertCell(0);
cell_1.innerHTML = "<input type='text' disable='' class='form-control' value=" + array[x] + ">";
x = x + 1;
var cell_2 = row.insertCell(1);
cell_2.innerHTML = "<span class='btn btn-default' onclick='showEditRow(this)'><img src='../../Content/images/1414409386_48-24.png' /></span>";
var cell_3 = row.insertCell(2);
cell_3.innerHTML = "<span class='btn btn-default' onclick='removeRow(this)'>X</apan>";
}
else {
//Detail Row
var rowDetails = table.insertRow(i);
var cell = rowDetails.insertCell(0);
//cell.colspan = "3";
cell.innerHTML = "<table style='background-color:rgb(98, 98, 98);color:black;border- radius: 5px;' margin:2%; >" +
"<tr>" +
"<td><input type='checkbox' id='"+x+"_appServer'/> Application Server</span></td>" +
"<td>" +
"<select id='" + x + "_appServerVersion'>" +
"<option>Application version</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td colspan='2'><input type='radio' name='database' id='"+x+"_emptyDb' onChange='enableOptions(1)'/>" +
" Empty Database</br><input type='radio' name='database' id='" + x + "_instalationSlt' onChange='enableOptions(2)'/> Something Databse</td>" +
"</tr>" +
"<tr id='emptyDB'>" +
"<td>" +
"Oracle Version"+
"<select id='JS_OraVersion' name='" + x + "_oraVersion' style='width:100%'>" +
"<option>Ora version</option>" +
"</select>" +
"</td>" +
"<td>" +
"Character Set" +
"<select id='JS_ChaSet' name='" + x + "_ChaSet' style='width:100%'>" +
"<option>Cha Set</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr id='dbImport'>" +
"<td>" +
"Something version" +
"<select id='JS_ImportVersion' name='" + x + "_ImportVersion' style='width:100%'>" +
"<option>Something version</option>" +
"</select>" +
"</td>" +
"<td>" +
"Something Charachter" +
"<select id='JS_ImportChaSet' name='" + x + "_ImportChaSet' style='width:100%'>" +
"<option>Something Cha</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td colspan='2'>" +
"Additional Requests </br>" +
"<textarea rows='4' id='" + x + "_specialReq' cols='37'> </textarea>" +
"<td/>"+
"</tr>"+
"</table>";
rowDetails.style.display = 'none';
Lock();
}
}
document.getElementById("instalationTable").style.display = "block";
}
i'm populating a form on the above table row, that collects some data to continue. to collect data i'm using following function which works fine with Google chrome but not with Internet explorer..
function getAllData() {
var StringtoSent = "";
for (i = 0; i < (elementsInTable.length) ; i++) {
var InsId = elementsInTable[i];
var _appServer = document.getElementById((i + 1) + "_appServer").checked;
var _appServerVersionDropDown = document.getElementById((i + 1) + "_appServerVersion");
var _appServerVersion = _appServerVersionDropDown.options[_appServerVersionDropDown.selectedIndex].value;
var _emptyDb = document.getElementById((i + 1) + "_emptyDb").checked;
var _instalationSlt = document.getElementById((i + 1) + "_instalationSlt").checked;
var _oraVersionDropDown = document.getElementsByName((i + 1) + "_oraVersion")[0];
var _oraVersion = _oraVersionDropDown.options[_oraVersionDropDown.selectedIndex].value;
var _ChaSetDropDown = document.getElementsByName((i + 1) + "_ChaSet")[0];
var _ChaSet = _ChaSetDropDown.options[_ChaSetDropDown.selectedIndex].value;
var _ImportVersionDropDown = document.getElementsByName((i + 1) + "_ImportVersion")[0];
var _ImportVersion = _ImportVersionDropDown.options[_ImportVersionDropDown.selectedIndex].value;
var _ImportChaSetDropDown = document.getElementsByName((i + 1) + "_ImportChaSet")[0];
var _ImportChaSet = _ImportChaSetDropDown.options[_ImportChaSetDropDown.selectedIndex].value;
var _specialReq = document.getElementById((i + 1) + "_specialReq").value;
StringtoSent = StringtoSent + "," + InsId + "," + _appServer + "," + _appServerVersion + "," + _emptyDb + "," + _instalationSlt + "," + _oraVersion + "," + _ChaSet + "," + _ImportVersion + "," + _ImportChaSet + "," + _specialReq + "|";
//return StringtoSent;
document.getElementById("ActivityDescription_instalationDetails").value = StringtoSent;
}
}
following image shows the error that im getting when it is ruining on VS 2012s IIS Express.
for (i = 0; i < (elementsInTable.length) ; i++) {
is the place that indicates as the error place . it always highlight the "elementsInTable.length" code segment.
Actually this error message elaborate nothing. i found some articles about the same error but occurring when trying to change the inner HTML of an element. but those solutions are not compatible for this situation.. Please help me with the problem
thanks in advance
Finally i found the Error
cell.innerHTML = "<table style='background-color:rgb(98, 98, 98);color:black;border- radius: 5px;' margin:2%; >" +
in above line i mistakenly added a CSS attribute "margin:2%;" in to a wrong place. Google chrome is intelligence enough to manage the situation and proceed the activity but Internet Explorer is not. as i found, this is the fact that prompt same error in different situations.
EG:
http://www.webdeveloper.com/forum/showthread.php?22946-innerHTML-amp-IE-Unknown-Runtime-Error
http://www.webdeveloper.com/forum/showthread.php?22946-innerHTML-amp-IE-Unknown-Runtime-Error
So if you got any unknown error in your Java Script code which uses "element.InnerHTML" or "document.Write" its better to check whether your tags are properly closed.
and i found several other situations that is generating same error
IE shows run time error for innerHTML
InnerHTML issue in IE8 and below
most of the times you can avoid this error by following W3C tag recommendations (http://www.w3.org/TR/html401/struct/global.html).