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>
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 have code shown below for a project where I insert list elements using javascript and for click on each element I have to call a function. However, it does not seem to work.
var c = document.getElementById("content");
c.innerHTML += "<ul>";
for(var j = 0; j<5; j++){
c.innerHTML += "<li id = '" + j + "'>some stuff"+j+"</li>";
document.getElementById(j).addEventListener("click", function(){ alert('this is test'); }, false);
}
c.innerHTML += "</ul>";
<div id = "content"> </div>
Why is the click event not being triggered? How can I make this work?
Create a function and use it onclick. You can also pass this(the element) as argument to the function where you can get the object attributes in that function.
var c = document.getElementById("content");
c.innerHTML += "<ul>";
for(var j = 0; j<5; j++){
c.innerHTML += "<li id = '" + j + "' onclick='alertMe(this)'>some stuff"+j+"</li>";
}
c.innerHTML += "</ul>";
function alertMe(obj){
alert('this is test from '+obj.id);
}
<div id = "content"> </div>
addEventListener Method:-
document.getElementById can only be called once you have append it into your DOM. before appending to the DOM you cant access it
If you still want to use addEventListener you can achieve by adding listener after appending the element like below
var c = document.getElementById("content");
c.innerHTML += "<ul>";
for(var j = 0; j<5; j++){
c.innerHTML += "<li id = '" + j + "'>some stuff"+j+"</li>";
document.getElementById(j).addEventListener("click", function(){ alert('this is test'); }, false);
}
c.innerHTML += "</ul>";
<div id = "content"> </div>
var c = document.getElementById("content");
c.innerHTML += "<ul>";
for (var j = 0; j < 5; j++) {
c.innerHTML += "<li id = '" + j + "'>some stuff" + j + "</li>";
}
c.innerHTML += "</ul>";
for (var j = 0; j < 5; j++) {
document.getElementById(j).addEventListener("click", function() {
alert('this is test');
}, false);
}
<div id="content"> </div>
The reason the OP doesn't work is because of this:
c.innerHTML += "<li id = '" + j + "'>some stuff"+j+"</li>";
When you concatenate to the innHTML property like that, the element content is first serialised, which removes any listeners that aren't inline (e.g. those added by addEventListener). So the only one remaining at the end of the loop is the last one.
But then you do:
c.innerHTML += "</ul>";
which removes the last one too.
Far better to build a single string of markup and use innerHTML once.
Consider: what should the browser do with the opening UL tag until the closing tag is entered? You've added invalid markup to the document, so it has to use error correction to make something work, so you might end up with a structure that isn't what you expected.
For the listeners, you can include them in-line with the rest of the markup so they survive being serialised and parsed.
Alternatively, use DOM methods to create the elements and stop using innerHTML.
function doClick(){
alert('this is a test ' + this.id);
}
window.onload = function() {
var c = document.getElementById("content");
var list = document.createElement('ul');
for(var j = 0; j<5; j++){
var li = list.appendChild(document.createElement('li'));
li.textContent = 'some stuff ' + j;
li.id = j;
li.addEventListener('click', doClick, false);
}
c.appendChild(list);
};
<div id="content"></div>
Try understand following magic
var c = document.getElementById("content");
c.innerHTML += "<ul>";
for(var j = 0; j<5; j++){
c.innerHTML += "<li id = '" + j + "'>some stuff"+j+"</li>";
}
c.innerHTML += "</ul>";
setTimeout(function () {
for(var j = 0; j<5; j++){
document.getElementById(j).addEventListener("click", function(){ alert('this is test'); }, false);
}
});
<div id = "content"> </div>
I want to add class " hidden" in many divs of the same id.
function show_wzorce(x) {
document.getElementById("" + x + "").className += " hidden";
var divs = document.getElementById("" + x + "");
for (var i = 0; i < divs.length; i++) {
divs[i].className += " hidden";
}
}
ID has to be unique. You can do the same thing but with getElementsByClassName (there is a "s" after element)
Your code should look something like this:
function show_wzorce(x) { // assuming x is string
var divs = document.getElementsByClassName(x); //this returns an HTML Collection. But works as an array
for (var i = 0; i < divs.length; i++) {
divs[i].className += " hidden";
}
}
I was playing around with tables and having text change as you mouse over each table. This code I have now works to change the first table's text but I am not sure how to get it to work for the other tables as well...
<script type="text/javascript">
function highlight(id) {
document.getElementById("name").innerHTML = "SF";
}
function unhighlight(id) {
document.getElementById("name").innerHTML = "Giants";
}
for (i = 0; i < 5; i++) {
document.write('<table width="300" id="i" onmouseover="highlight(i);" onmouseout="unhighlight(i);">');
document.write('<tr>');
document.write('<td id="name">Giants</td>');
document.write('<td>5</td>');
document.write('</tr>');
document.write('</table>');
}
</script>
It is because id name is repeated in all the tables. so document.getElementById("name") will always find the first element with id name. You have to make it unique in each table then it should work fine. Also you have to pass something to highlight method to identify the mouse over/out table.
function highlight(id) {
document.getElementById("name" + id).innerHTML = "SF";
}
function unhighlight(id) {
document.getElementById("name" + id).innerHTML = "Giants";
}
for (i = 0; i < 5; i++) {
document.write('<table width="300" id="i" onmouseover="highlight(' + i + ');" onmouseout="unhighlight(' + i + ');">');
document.write('<tr>');
document.write('<td id="name' + i + '">Giants</td>');
document.write('<td>5</td>');
document.write('</tr>');
document.write('</table>');
}