I have the below problem where I am trying to get the code from appleImg and pearImg to be put into an html element called middleCell should a button be clicked and based off a value of an input (input1). How can I make this work?
<table border="1">
<tr>
<td>
<input id="input1">
<button id="leftButton" onclick="fruitTest();">Enter</button>
</td>
<td>
<p id="middleCell">Hello</p>
</td>
<td>
<button id= "clearButton" onclick="clearBox();">Clear</button>
</td>
</tr>
</table>
var appleImg = "<img src="https://codehs.com/uploads/afcd3bf7ea7baf3f7d571c6e24c352af">";
var pearImg = "<img src="https://codehs.com/uploads/e0c442f8c020685fc8016f15c2547f1e">";
// Add your JavaScript code bel
var middleCell = document.getElementById("middleCell");
function fruitTest(){
var myInput = document.getElementById("input1");
var inputValue = myInput.value;
if (inputValue > 100){
middleCell.innerHtml = appleImg;
} else if (inputValue < 0){
middleCell.innerHtml = pearImg;
}
}
function clearBox (){
middleCell.innerHtml = "";
}
I wanted the value of the middleCell to show the images based of what was entered. When 101 is enetered and button clicked, the appkle image should show up.
Also, when clicking clear, the middleCell shoould be clear. Please help!
3
Answers
Try this:
I changed innerHtml to innerHTML
Plus I added parseInt() around inputValue to make sure it was converted to a number
After doing some tests here, I think that you can use the following if you need to keep the text + image:
I like this method cause you can insert the HTML (even if doing this can not be the best option for all the cases :p) in different positions
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
Instead of doing the
And to remove the image after clicking on the clear button, one approach should be getting the added image by using
querySelector
(https://developer.mozilla.org/pt-BR/docs/Web/API/Document/querySelector):You should use
innerHTML
instead ofinnerHtml
and also I wouldn’t recommend to hardcode element as a string. You can create elements using the corresponding JS function instead. Also, consider usingconst
andlet
instead ofvar
.Please let me know if this helps.