This question already has answers here:
Why is document.GetElementById returning null [duplicate]
(6 answers)
Closed 8 years ago.
im trying to build a minesweeper in html and the javascript isnt woking
heres my html
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type = "text/css"
href = "minesweeper.css" >
</head>
<body>
<table id = "i" ></table>
<script src = "minesweeper.js" ></script>
</body>
</html>
here is the css
td{
border: 2px outset #000000;
width:25px;
height: 25px;
background-color: #cfcfcf;
}
and here is the javascript (minesweeper.js)
var gameBox = document.getElementById("i").innerHTML;
console.log(gameBox);
for ( var i = 0 ; i < 3 ; i++ ) {
gameBox += "<tr>";
console.log(gameBox);
for ( var j = 0 ; j < 3 ; j++ ) {
gameBox += "<td id = '" /*+ i*/ + j + "'></td>";
}
gameBox += "</tr>";
}
and all i get is a blank page
heres a link to the page
http://borisute.com/geshem/2013/mkeller/minsweeper.html
(it has some more code i didnt include b/c its not relevant to the above problem
You still need to put the gamebox onside the html at the end of the script:
var gameBox = document.getElementById("i").innerHTML;
for ( var i = 0 ; i < 3 ; i++ ) {
gameBox += "<tr>";
for ( var j = 0 ; j < 3 ; j++ ) {
gameBox += "<td id = '" + i + j + "'></td>";
}
gameBox += "</tr>";
console.log(gameBox);
}
document.getElementById("i").innerHTML = gameBox;
You gamebox variable is nothing but this at the end of the for loop
<tr><td id = '0'></td><td id = '1'></td><td id = '2'></td></tr><tr><td id = '0'></td><td id = '1'></td><td id = '2'></td></tr><tr><td id = '0'></td><td id = '1'></td><td id = '2'></td></tr>
Also, you are not assigning to any element. You are only creating the variable.
Related
I'm trying to add a button in javascript file without using HTML bacsue I need to have it in the column inside the loop, but when I click on the button to call the function it shows the error that its looking on that button in HTML file!
how could I fix that?
function success(name) {
let info = "<div class='infoTable'>";
for (let i = 0; i < name.length; i++) {
info += "<div class='info'>";
info += "<div class='fcol'>" + (i+1) + "</div>";
info += "<div class='scol'>" + name[i].item + "</div>";
info += "<div class='fcol'>" + name[i].quantity + "</div>";
info += '<button onclick="deletee(\'' + name[i].ID + '\')"> Delete This<button />';
info += "</div>";
}
info += "</div>";
printItems.innerHTML = info;
}
this is the function
function deletee(id){
let url = "server/delete.php?id=" + id;
console.log(url);
fetch(url, { credentials: 'include' })
.then(response => response.text())
.then(getList)
}
this is the error
(index):1 Uncaught ReferenceError: deletee is not defined
at HTMLButtonElement.onclick ((index):1)
onclick # (index):1
The best solution in this case is using document.createElement: https://www.w3schools.com/jsref/met_document_createelement.asp
It's better practice than converting a string to DOM Elements.
Since you did not post all your code, we cannot assist further if we cannot see the function you are trying to execute.
The reason why I am suggesting using JS and not converting a string to DOM, is most IDE's will identify missing, misspelt, or incorrectly used functions. Which could've been your mistake.
Here is an example:
var colsToAdd = 5;
var rowsToAdd = 25;
function FillTable() {
//Get existing table or create a new one. Append to parent if create
var table = document.getElementById("testTable");
//Clear table
table.innerHTML = "";
//Create your rows using a for loop
for (var i = 0; i < rowsToAdd; i++) {
var row = document.createElement("TR");
table.appendChild(row);
//Create your columns using a for loop
for (var k = 0; k < colsToAdd; k++) {
{
var col = document.createElement("td");
row.appendChild(col);
if (k == colsToAdd - 1) {
var button = document.createElement("button");
button.type = "button";
//Button click event is an anonymous function
button.onclick =
function(r) {
return function() {
table.removeChild(r);
}
}(row)
button.innerHTML = "Delete";
col.appendChild(button);
} else {
col.innerHTML = "row " + i + " column " + k;
}
}
}
}
}
table {
border: 1px solid #000;
margin: 1em;
}
td {
border: 1px solid #000;
padding: 1em;
}
<div>
<h1>Heading</h1>
<button onclick="FillTable()">Fill table</button>
<table id="testTable">
</table>
</div>
I have a table and when I clicked on leftmost column's number like 1,2,3... I want their respective rightmost column 0 to increase like 1,2,3,4,5...(Increase by 1 on every click.)
var ms=document.getElementById('message');
window.onload = build;
var myArray = ["Laurence", "Mike", "John", "Larry", "Kim", "Joanne", "Lisa", "Janet", "Jane"];
var message = document.getElementById('message');
function build() {
var html = "<h1>My Friends Table</h1><table>";
for (var x = 0; x < myArray.length; x++) {
html += '<tr data-row="' + x + '" data-vote="0"><td class="box" >' + (x + 1) + '</td><td>' + myArray[x] + '</td><td>0</td></tr>';
}
html += '</table>';
document.getElementById('output').innerHTML = html;
var elbox = document.querySelectorAll('#output .box');
var a;
var v;
for (var x = 0; x < elbox.length; x++) {
elbox[x].onclick = function () {
console.dir(this);
a = this.closest('[data-row]').getAttribute('data-row');
console.log(myArray[a]);
message.innerHTML = myArray[a] + " is on row #" + a;
v = this.closest('[data-vote]').getAttribute('data-vote');
v++;
console.log(v);
this.parentElement.lastElementChild.innerText=v;
}
}
}
td {
border: 1px solid #ddd;
padding: 10px;
}
<html>
<head>
<title>Complete JavaScript Course</title>
</head>
<body>
<div id="message">Complete JavaScript Course</div>
<div id="output"></div>
</body>
</html>
I have set v++ but why the value of v is not increasing? I am still seeing value as 1. To update the innertext,I have used
this.parentElement.lastElementChild.innerText=v;
Since <tr> is parent of td and i used this.parentElement.lastElementChild.innerText=v; why its just stuck to 1 on every click?Why it is not increasing after one?
Every time you click it is based on data-vote attribute value of the first td of the row.
You do modify the innerText of the right column but after that you should do something like this to modify the data-vote attribute also:
this.parentElement.firstElementChild.dataset.vote=v;
I would like to create, tr, td through javascript, and make a simple calendar from day 1 to day 30.
I created an example with console.log() for trying to understand for myself.
When I tried to switch from console.log() to document.getlementById("calendar") for printing on html, it did not print.
The error showed that
calendar.js:3 Uncaught ReferenceError: Invalid left-hand side in
assignment
my understanding with console.log():
for (var i = 1; i <= 5; i++) {
//open tr tag
console.log("<tr>");
for(var i = 1; i <= 30; i++){
var days = "<td>" + i + "</td>";
//print 1 to 31 with td tag
console.log(days);
//if i divide by 7 and remainder is 0
if(i % 7 == 0 || i == 31){
console.log("</tr>");
console.log("<tr>");
}
};
console.log("</tr>");
};
Actual my code with document.getElementById("calendar")
for (var i = 1; i <= 5; i++) {
//open tr tag
document.getElementById("calendar") += "<tr>";
for(var i = 1; i <= 30; i++){
var days = "<td>" + i + "</td>";
//print 1 to 31 with td tag
document.getElementById("calendar") += days;
//if i divide by 7 and remainder is 0
if(i % 7 == 0 || i == 31){
document.getElementById("calendar") += "</tr>";
document.getElementById("calendar") += "<tr>";
}
};
document.getElementById("calendar") += "</tr>";
};
my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<div >
<table>
<tr>
<th>S</th>
<th>M</th>
<th>T</th>
<th>W</th>
<th>T</th>
<th>F</th>
<th>S</th>
</tr>
<span id="calendar">
</span>
</table>
</div>
<script src="js/calendar.js" ></script>
</body>
</html>
The error showed that
Uncaught ReferenceError: Invalid left-hand side in assignment
First, you can't have a <span> inside your table where you placed it. A table can only hav a <tr> at this place. But you don't need this span at all, you can just append the string direcly to the table, so I moved the ID to the <table>-tag.
I also used a variable to build all the HTML and after it's all built I inserted it with insertAdjacentHTML() at the end of the table.
var table = document.getElementById("calendar");
var htmlstring = "";
for (var i = 1; i <= 5; i++) {
//open tr tag
htmlstring += "<tr>";
for (var i = 1; i <= 30; i++) {
var days = "<td>" + i + "</td>";
//print 1 to 31 with td tag
htmlstring += days;
//if i divide by 7 and remainder is 0
if (i % 7 == 0 || i == 31) {
htmlstring += "</tr>";
htmlstring += "<tr>";
}
};
htmlstring += "</tr>";
};
//console.log(htmlstring);
table.insertAdjacentHTML('beforeend', htmlstring)
<div>
<table id="calendar">
<tr>
<th>S</th>
<th>M</th>
<th>T</th>
<th>W</th>
<th>T</th>
<th>F</th>
<th>S</th>
</tr>
</table>
</div>
I'm using Fusion Tables to store a URL to my Google Drive Photos (stored in the column Link).
I'm using JavaScript to query Fusion Tables to get all the URLs and then create a table with 3 items picked randomly from the data.
The code I add underneath let me see 3 first photos ... I have tried to switch the line
contentStr += "<td><img src=" + item[j]+"></td>";
to
contentStr += "<td><img src=" + randomElement[j]+"></td>";
but it doesn't work. Does anyone can help me please?
<head>
<title>Test</title>
</head>
<body>
<div id="content"></div>
<script>
function handler(response) {
var maxFoto = response.rows.length
var contentStr = "<table>";
for (var i = 0; i < 3; i++) {
var item = response.rows[i];
var randomFoto = Math.floor(Math.random()*maxFoto);
var randomElement = item[randomFoto];
contentStr += "<tr>";
for (var j = 0; j < item.length; j++) {
contentStr += "<td><img src=" + item[j]+"></td>";
}
contentStr += "</tr>";
}
contentStr += "</table>";
document.getElementById("content").innerHTML = contentStr;
}
</script>
<script src="https://www.googleapis.com/fusiontables/v2/query?sql=SELECT%20Link%20FROM%20MYidTABLE&key=MYKEY&callback=handler&viewable=true"></script>
</body>
</html>
I give myself an answer ... code below works perfect!
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="content"></div>
<script>
function handler(response) {
var maxFoto = response.rows.length
var contentStr = "<table>";
for (var i = 0; i < 3; i++) {
var randomFoto = Math.floor(Math.random()*maxFoto);
var item = response.rows[randomFoto];
contentStr += "<tr>";
for (var j = 0; j < item.length; j++) {
contentStr += "<td><img src=" + item[j]+"></td>";
}
contentStr += "</tr>";
}
contentStr += "</table>";
document.getElementById("content").innerHTML = contentStr;
}
</script>
<script src="https://www.googleapis.com/fusiontables/v2/query?sql=SELECT%20Link%20FROM%20MYTABLEID&key=MYKEY&callback=handler&viewable=true"></script>
</body>
</html>
I'm trying to figure out a way to retrieve and display the value of a div tag that is created with a 2D array using JavaScript. I figured either onclick or onmouseover would work but neither would in this approach. I would like to avoid creating 49 functions that does the same thing (just displaying the 'cell' the mouse is over).
<style type="text/css">
.float {float: left;}
.clear {clear:both;}
div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
<div id="grid"></div>
<div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(cellId)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
// ???
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
Thanks!
You can simply get the cell id by passing this.id into the function.
Try this:
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
console.log(cellId);
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
Right now you have set up each cell element to call the function displayMe whenever the mouseover event occurs. When you call that function, you are passing the variable cellId as an argument. The problem is when that function is called, cellId is not defined. You can see this error pop up in your browser's developer console ("Uncaught ReferenceError: cellId is not defined").
You probably want to pass the cell element's id property, which you define dynamically here: id='area" + i + j + "'. You can use the id property of an element to look up the element (as you have done already), and get the text it contains via textContent.
To pass the cell element's id property, you need to use the this variable, like so: this.id. this will refer to the element that is triggering the event. So, if you change your onmouseover value of your div element to this: onmouseover='displayMe(this.id)', it will pass the appropriate value to your displayMe function, allowing you to do something like this:
function displayMe(cellId) {
document.getElementById('bucket').innerHTML = document.getElementById(cellId).textContent;
}
With these adjustments, your code will look like this in its entirety:
<style type="text/css">
.float {float: left;}
.clear {clear:both;}
div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
<div id="grid"></div>
<div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
document.getElementById('bucket').innerHTML = document.getElementById(cellId).textContent;
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>