I'm building a memory game in HTML & JS where you guess 2 different images and try to pick 2 same ones.
I'm stuck with putting an onclick function to a hidden image.
Here is my code so ill try to explain better...
var table = '';
for(var i = 0; i < 4; i++){
table += '<tr>';
for(var j = 0; j < 3; j++){
table += '<td align="center"><img src="./pics/image_part_00' + Math.floor((Math.random() * 6) + 1) + '.jpg";" width="100px"" onclick="clicked(this);" style="visibility: hidden;"></td>';
}
table += '</tr>';
}
document.getElementById('theGame').innerHTML = '<table border=1 cellpadding="10" class="tabela1">' + table + '</table>'
Now what im trying to do is to overwrite that visibility: hidden; so the image is visible when clicked....
And here is the function
function clicked(element){
element.style.visibility = "visible";
}
but it doesn't work because with that element.style.visibility im changing the visibility of a table cell.
Anyone got a solution? I'm probably missing something and can't figure it...
NOTE: It's a school assignment so it has to be in a table.
Here is a some fixed javascript. when you catch onclick event, it won't work on hidden elements. So I move event listener onto td:
var table = '';
for(var i = 0; i < 4; i++){
table += '<tr>';
for(var j = 0; j < 3; j++){
table += '<td align="center" onclick="click_it(this)">
<img src="./pics/image_part_00' + Math.floor((Math.random() * 6) + 1) + '.jpg"
width="100px" style="visibility: hidden"></td>';
}
table += '</tr>';
}
document.getElementById('theGame').innerHTML = '<table border=1 cellpadding="10" class="tabela1">' + table + '</table>';
function click_it(cell){
var image = cell.children[0];
image.style.visibility = 'visible';
}
You can search for the img child of the table cell
var child = element.childNodes;
The var child will return an array of elements, then you just need to access to the position that the is, and change the visibility attribute:
child[1].style.visibility = "visible";
You can try below,
just played a trick to match element id dynamically
to make it visible.
Added on click to td instead of image.
added id to image.
here is the code
<div id="theGame">
var table = '';
for (var i = 0; i < 4; i++) {
table += '<tr>';
for (var j = 0; j < 3; j++) {
table += '<td align="center" onclick="clicked(' + j + ')"> <img id=img_' + j + ' src="./pics/image_part_00' + Math.floor((Math.random() * 6) + 1) + '.jpg;" width="100px" style="visibility: hidden;"> </td>';
}
table += '</tr>';
}
document.getElementById('theGame').innerHTML = '<table border=1 cellpadding="10" class="tabela1">' + table + '</table>'
function clicked(element) {
document.getElementById('img_' + element).style.visibility = "visible";
}
Related
I created a simple function in JS that generates a table. Now I want to do this: when I click on some cell of the table, the page will alert the value what is inside the cell: variable b, as you can see in the code. I tried it, but I didn´t managed it. is inside the code. I also used Jquery.
The code: JS
function gen() {
var rowData = '';
for (var a = 0; a < 5; a++) {
rowData += '<tr>';
for (var i = 0; i < 3; i++) {
rowData += '<td>';
rowData += b;
rowData += '</td>';
b++;
}
rowData += "</tr>";
}
$('#myTableId2').append(rowData);
}
HTML:
<table id="myTableId2"> </table>
<button onclick="gen()">Generate</button>
rowData += '<td onclick="alert(this.innerHTML)">';
I see you're using jQuery. You can attach a click() event to each <td> element as I do below.
Note that since b is undefined in your example, I took the liberty of giving it a random value for illustrative purposes.
function gen() {
let b = Math.floor(Math.random() * 1000) + 1; //generate random value
var rowData = '';
for (var a = 0; a < 5; a++) {
rowData += '<tr>';
for (var i = 0; i < 3; i++) {
rowData += '<td>';
rowData += b;
rowData += '</td>';
b++;
}
rowData += "</tr>";
}
$('#myTableId2').append(rowData);
//attach the click event using jQuery
$("td").click(function(){alert(this.innerText)});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId2"> </table>
<button onclick="gen()">Generate</button>
I've been working on a functionality that involves the creation of a HTML table using jquery that will display a list of accounts dynamically on page load, that's something I achieved without problems.
However, I've also asked to add an "onclick" event to each row that will redirect me to another web page, but that will depend on a parameter that I need to pass. Here's my code:
$(document).ready(function() {
var x = ['Visa-1234', 'Amex-9182', 'Visa-8162', 'Visa-9554'];
var message = 'No accounts found';
if (x.length > 0) {
message = 'Select an account to display the rewards information: ';
}
$('#message').text(message);
var tableContentHtml = '<table class="table-fill"><thead><tr><th class="text-left">Account</th></tr></thead><tbody class="table-hover">';
for (var i = 0; i < x.length; i++) {
tableContentHtml += '<tr><td class="text-left" onclick="goAnotherWebPage()">' + x[i] + '</td></tr>';
}
tableContentHtml += '</tbody></table>';
$(tableContentHtml).appendTo('#container');
});
function goAnotherWebPage(account) {
//do some logic here
}
The method "goAnotherWebPage" should receive the same account ID that is being displayed, I have no problem with that, the problem comes when I pass the x[i] as parameter on the table creation:
onclick="goAnotherWebPage(x[i])"
That is not working, it says that the account is not defined.
Can somebody give me a hint or provide help in order to achieve this? Thanks in advance!
Try this out
for (var i = 0; i < x.length; i++) {
tableContentHtml += '<tr><td class="text-left" onclick="goAnotherWebPage(\'' + x[i] + '\')">' + x[i] + '</td></tr>';
}
$(document).ready(function() {
var x = ['Visa-1234', 'Amex-9182', 'Visa-8162', 'Visa-9554'];
var message = 'No accounts found';
if (x.length > 0) {
message = 'Select an account to display the rewards information: ';
}
$('#message').text(message);
var tableContentHtml = '<table class="table-fill"><thead><tr><th class="text-left">Account</th></tr></thead><tbody class="table-hover">';
for (var i = 0; i < x.length; i++) {
tableContentHtml += '<tr><td class="text-left" onclick="goAnotherWebPage(\'' + x[i] + '\')">' + x[i] + '</td></tr>';
}
tableContentHtml += '</tbody></table>';
$(tableContentHtml).appendTo('#container');
goAnotherWebPage = function(account) {
console.log(account);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"></div>
<div id="container"></div>
Hope this will help you.
I try to understand what do you need and i create a simple demo for you
$(document).ready(function() {
var x = ['Visa-1234', 'Amex-9182', 'Visa-8162', 'Visa-9554'];
var message = 'No accounts found';
if (x.length > 0) {
message = 'Select an account to display the rewards information: ';
}
$('#message').text(message);
var tableContentHtml = '<table class="table-fill"><thead><tr><th class="text-left">Account</th></tr></thead><tbody class="table-hover">';
for (var i = 0; i < x.length; i++) {
tableContentHtml += '<tr><td class="text-left redirect">' + x[i] + '</td></tr>';
}
tableContentHtml += '</tbody></table>';
$(tableContentHtml).appendTo('#container');
});
$('body').on('click', '.redirect', function (e) {
value = $(this).html();
console.log(value);
// do your logic here
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"></div>
<div id="container"></div>
Alright, some information right off the bat, I have a table that is dynamically being created.
The table looks roughly like this :
|item__ | price | category | category | category | category | picture |
|chicken| $20 | _______ |_ ______ | _______ | _______ | 1000.png|
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
if (j == 6) {
table += "<td>" + "<img src='CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";
} else if {
table += "<td>" + array[i][j];
}
table += "<tr>";
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
This is the code that I have at the moment, where array is a 2D array. And every (6th column in the row, I want it to be an image) When runned, this does not display any table whatsoever.
In the code below
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
table += "<td>" + array[i][j];
}
table += "<tr>";
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
Without the if statement and the additional img content, the table displays perfectly, but obviously 1000.png shows up instead of the actual image.
CSV_Photos is a folder where the image is stored at, essentially in the same folder. I don't know what is wrong, any help or leads are appreciated.
Edit: So the 2nd part of the code I have works perfectly, It generates a table for me. But at every 6th column of a row is a picture name (1000.png) and its in the folder CSV_Photo. I want it to no display as 1000.png, but instead the picture. The 1st section of code is my attempt to make it an image, but no table is created so I'm guessing there is something wrong with this line table += "" + <"img src= 'CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";
I think there are several problems in your code that needs to be fixed :
You are not appending the td elements inside the tr but directly
inside the table, you need to move the line table += "<tr>";
before the nested loop.
And you are not specifying closing tags for <td> elements so when
you include the img tag it will mess up the layout.
Another thing just inverse the use of " and ' in your img tag
definition because HTML uses ".." to define attributes.
Here's how should be your code:
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
table += "<tr>";
for (var j = 0; j < array[i].length; j++) {
if (j == 6) {
table += "<td>" + '<img src="CSV_Photos/' + array[i][j] + '" style ="width:500px;height:300px"></td>';
} else if {
table += "<td>" + array[i][j] + "</td>";
}
}
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
Try:
var array = csvpls();
var table = "<table>";
for (var i = 0; i < array.length; i++) {
table += "<tr>";
for (var j = 0; j < array[i].length; j++) {
table += "<td>" + array[i][j];
}
table += "</tr>";
}
table += "</table>";
document.getElementById("Invtable").innerHTML = table;
If you wanted the image to be on the 2nd row, 3rd cell the condition should be:
if (i === 1 && j === 2) {...
If you want the whole 2nd row with the same image in each cell then it should be:
if (i === 1) {...
If you want a entire 3rd column to have the same image then it would be:
if (j === 2) {...
If it's a different image for every cell, then name each file by table coordinates like this...
img1-2.png
...then change the string that renders an image inside a cell as:
table += `<td><img src='http://imgh.us/img${i}-${j}.png' style ='width:50px;height:50px'></td>`
Or if I understand correctly, the array already has the filenames. If that's true, then the string should be...
table += `<td><img src='http://imgh.us/${array[i][j]}' style ='width:50px;height:50px'></td>`
... and the array would be something like this:
var array = [
['rt','AD','1000.png','uy','ii'],
['rt','AD','1001.png','uy','ii'],
['rt','AD','1002.png','uy','ii']
];
BTW, I had to do some changes to the code in order for it to work since it's only a partial code you provided, but the gist of it is the condition of course.
Also you'll notice the strange syntax of the strings, that's ES6 template literals or "strings on steroids".
Demo
var array = cvpls();
var table = ``;
for (var i = 0; i < array.length; i++) {
table += `<tr>`;
for (var j = 0; j < array[i].length; j++) {
if (i === 1 && j === 2) {
table += `<td><img src='http://imgh.us/statik.gif' style ='width:50px;height:50px'></td>`;
} else {
table += `<td>${array[i][j]}</td>`;
}
}
table += `</tr>`;
document.getElementById("Invtable").innerHTML = table;
}
function cvpls() {
return array = [
[4, 5, 6, 9, 2],
['img', 'img', 'img', 'img', 'img'],
['d', 'b', 'g', 'i', 'o']
];
}
td {
border: 1px solid black
}
<table id='Invtable'></table>
I have dynamic generated columns that have variable width according to the user screen size:
How can I split these divs in rows?
You don't need to split them into rows. Many responsive layouts require column units to exceed 12 in a row. This is known as column wrapping in Bootstrap.
If the content of the columns varies in height, you will need to use responsive resets to prevent the height problem. This will force a "wrap" every X number of columns, based on the tier.
Clearfix Demo (responsive tiers)
There is also a CSS-only variation of the 'clearfix'.
Bootstrap row has a length of twelve, this means everything above twelve will be placed under the row. Unfortunately this is not looking nice. I do not know how you make the those divs. Assuming you pass an array to your front-end you can use javascript based on how many divs.
there is probaly a better way. I am new to programming, but would think of something like this:
Note that you need to change yourArray to the variable name of your array.
<div id="allRows">
<script>
var mqxs = window.matchMedia( "(max-width: 767px)" );
var mqsm = window.matchMedia( "(min-width: 768px)" );
var mqmd = window.matchMedia( "(min-width: 992px)" );
var mqlg = window.matchMedia( "(min-width: 1200px)" );
var html = '<div class="row">';
if (mqxs.matches){
var max = 2;
var count = 1;
for(var i=0; i < yourArray.length; i++){
if (var > max){
html += "</div>";
html+= "<div class='row'>";
count = 1;
}
html+= "<div class= 'col-xs-6>yourArray[i]'</div>";
count += 1;
}
}else if (mqsm.matches){
var max = 3;
var count = 1;
for(var i=0; i < yourArray.length; i++){
if (var > max){
html += "</div>";
html+= "<div class='row'>";
count = 1;
}
html+= "<div class= 'col-sm-4'>yourArray[i]'</div>";
count += 1;
}
}}else if (mqmd.matches){
var max = 4;
var count = 1;
for(var i=0; i < yourArray.length; i++){
if (var > max){
html += "</div>";
html+= "<div class='row'>";
count = 1;
}
html+= "<div class='col-md-3'>yourArray[i]'</div>";
count += 1;
}
}else (mqlg.matches){
var max = 6;
var count = 1;
for(var i=0; i < yourArray.length; i++){
if (var > max){
html += "</div>";
html+= "<div class='row'>";
count = 1;
}
html+= "<div class= 'col-lg-2>yourArray[i]'</div>";
count += 1;
}
}
html += </div>
document.getElementById("allRows").innerHTML = html;
</script>
</div>
I want to create table using javascript and fill it with data. So I decided to use prompt method and loop while.
But when I try to load page I always get two error message in google chrome developer tools
Here is the code
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function onStart() {
var list = new Array();
var headers = new Array("Имя","Отчество","Фамилия","Дата рождения");
var i = -1;
while(true) {
var a = prompt("Имя","noname");
var b = prompt("Отчество","nomiddlename");
var c = prompt("Фамилия","nosurname");
var d = prompt("Дата рождения!",0);
if (confirm("Уверены что хотите добавить студента?")) {
i++;
list[i] = a + "-" + b + "-" + c + "-" + d;
}else{ break; };
}
tab = "<table>";
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
tab +="</table>";
document.write(tab);
};
</script>
</head>
<body onLoad = "onStart()">
</body>
What's the problem?
Your for loops seem to be mis-indented and not closed properly
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
Should be
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
}
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
Not directly related to your question, but you have a few other common javascript errors.
By not declaring variables with var, you are unintentionally creating global variables. While this probably isn't a huge issue on your page, but it is bad practice.
In addition, you should wrap your <th> tags you are appending inside of a <tr>, as the only "valid" element within a <table> is a <tr> (technically its tbody, thead, and tfoot, of which the only valid children is <tr>).
You're missing the closing } on your first loop:
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
}
I would go to guess he is trying to loop thru headers, followed by columns, then close the table. Not loop thru headers, and for each header add all rows. And, certainly not loop thru headers and for each header loop through all rows and close and write the table.
In your code onStart(){} method is not closed properly. Add one more "}" in front of the below code
</script>
</head>