I've created a 4x4 grid of <div>
s where you can click on the cells and be prompted by the browser to enter a number. If you enter text, the text is displayed in the grid you just clicked on.
I have it working with the following code:
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
But when I try to implement this feature as a function that is modelled on the above code, I cannot get the input from the prompt to be put into the innerHTML property. This is what I have tried:
function setText() {
this.innerHTML=prompt('Enter a number');
}
There seems to be an issue with the this.innerHTML
. Does anyone know how to make this
work in a function? I want the this
to refer to the <div>
that triggers the onclick event but it doesn't seem to do that.
Here is the HTML, CSS and Javascript I wrote:
function setText() {
this.innerHTML=prompt('Enter a number');
}
* {
margin: 0;
padding: 0;
}
section {
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
background-color: lightblue;
}
.grid {
display: grid;
gap: 2px;
grid-template-columns: repeat(4, 12vw);
grid-template-rows: repeat(4, 12vw);
font-size: 8vw;
}
.grid div {
background-color: green;
display: flex;
justify-content: center;
align-items: center;
color: white;
}
<section>
<div class="grid">
<div onclick="setText();"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
<div onclick="this.innerHTML=prompt('Enter a number')"></div>
</div>
<section>
Any help would be greatly appreciated.