How to replace a table cell value with a picture? - javascript

I've got a table output that is generated dynamically.
I've got a javascript function that is doing some coloring and replacement of cell values, which is fine (e.g. background becomes green when innerText==3; please find the sample code below).
Now I'm trying to insert a picture in those table cells that have innerText==9.
Is it possible to include this functionality in my function?
I tried with a pictureGrey declaration an assigned it to innerText, but this doesn't work.
Does anyone have an idea, can someone help me?
Thanks a lot in advance,
Gero B.
function ModifyData( ) {
var Elements=document.getElementsByTagName('td');
pictureGrey="Z_led_grey.gif";
for(var i=0;i<Elements.length;i++) {
if(Elements[i].innerText=='3') {
Elements[i].style.color='green';
Elements[i].style.background='green';
Elements[i].innerText=' ';
}
if(Elements[i].innerText=='9') {
Elements[i].innerText= pictureGrey ;
}
}
}

please check the below code.
function ModifyData( ) {
var Elements=document.getElementsByTagName('td');
pictureGrey="Z_led_grey.gif";
for(var i=0;i<Elements.length;i++) {
if(Elements[i].innerText=='3') {
Elements[i].style.color='green';
Elements[i].style.background='green';
Elements[i].innerText=' ';
}
if(Elements[i].innerText=='9') {
Elements[i].innerText=' ';
var img = document.createElement("img");
img.src=pictureGrey;
Elements[i].appendChild (img );}
}
}
demo link:
http://jsfiddle.net/asimshahiddIT/acz5xn3b/

You could create a new image element and append it in the element. Depending on if the data can subsequently change again you might need to check for the existence of the image first.
CSS
img.myFullSizeImageClass {
width: 100%;
height: 100%;
}
JavaScript
function ModifyData() {
var Elements = document.getElementsByTagName('td');
pictureGrey = "angular-icon.png";
for (var i = 0; i < Elements.length; i++) {
if (Elements[i].firstChild.nodeValue == '3') {
Elements[i].style.color = 'green';
Elements[i].style.background = 'green';
Elements[i].firstChild.nodeValue = ' ';
}
else if (Elements[i].firstChild.nodeValue == '9') {
Elements[i].firstChild.nodeValue = "";
var img = document.createElement("img");
img.src = pictureGrey;
img.className = 'myFullSizeImageClass'
Elements[i].appendChild(img);
}
}
}

Related

Displaying images with given URL in a json string on a html page

I am working on a project where I call a certain API and in response I get back a json string with all the information. I need to find a way using javascript to display this json string into a table format. I got a very basic version of this running. However, the problem I am having is that I cannot find a way to display a image in this block of code.
results.html file:
<!DOCTYPE HTML>
<html>
<head>
<title>
How to convert JSON data to a
html table using JavaScript ?
</title>
<h1>Results: </h1>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body style = "text-align:center;" id = "body">
<h3>Showing resuls for: {{searchQuery}}</h3>
<p>{{responseText}}</p>
<br><br>
<table align = "center"
id="table" border="1">
</table>
<div id="header"></div>
<script>
var el_up = document.getElementById("GFG_UP");
var list = [];
list = "{{responseText|escapejs}}";
//console.log(list);
var titles = []
for (var i = 0; i < list.length-8; i++) {
if(list[i] == 't' && list[i+1] == 'i')
{
var title = '';
for(var j = (i+8); list[j] != ","; j++) {
title += list[j];
}
i = j;
console.log(title + ", ")
titles.push(title)
}
}
console.log(titles)
var images = []
for (var i = 0; i < list.length-8; i++) {
if(list[i] == 'h' && list[i+1] == 't')
{
var image = '';
for(var j = (i); list[j] != ","; j++) {
image += list[j];
}
i = j;
console.log(image + ", ");
var img = new Image();
img.src = image.slice(0, -1);
images.push(img);
}
}
console.log(images)
var restaurants = []
for (var i = 0; i < list.length-17; i++) {
if(list[i] == 'r' && list[i+1] == 'e' && list[i+2] == 's')
{
var restaurant = '';
for(var j = (i+17); list[j] != ","; j++) {
restaurant += list[j];
}
i = j;
console.log(restaurant + ", ")
restaurants.push(restaurant)
}
}
console.log(restaurants)
function createTable(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
console.log(typeof(cellData))
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
})
table.appendChild(tableBody);
document.body.appendChild(table);
};
var a = [titles, restaurants, images]
console.log(a)
createTable(a);
</script>
</body>
</html>
The function createTable is the one in question. It displays the text parts correctly. Im not sure how to get it to display images given the URLs of those images in a table.
output HTML file:
HTML output
You should show us the API response you are working with here.
Another thing is your createTable function expects to get table data. But onclick on your button pass there #table ID. Not sure if it should be like this.
Also you could run your JS script when all page is loaded:
window.onload = () => {
// Your JS script which should do something after page is loaded.
}
Finally it comes to the images. I think that you are not using img tag anywhere so your images simply won't be visible in the table. If you would like to see them just create img element and put it into td.
Few advices (not related with your question):
stop using console.log so much, place debugger statement in your code and debug it like a pro, if you don't know how just look for it in youtube,
please put your attention to a code style, it is a bit messy, if you have real trouble with it use ESlint to fix it for you.
EDIT
About images - if you want to create DOM element for img use code below instead of current one:
var img = document.createElement("IMG");
Than you can set src and other things like alt and so on:
img.src = imgUrlString;

Javascript to change innerHTML function not working

I'm building an interface that consists of 9 cells in table. When a person mouses over a cell, I want other cells to become visible, and change the text content of some of the cells. I can do that just fine if I create individual functions to change the content of each cell, but that's crazy.
I want a single function to change the text depending on the cells involved. I created a function that can take n arguments, and loops through making changes based on the arguments passed in to the function. It doesn't work.
Code for the function is below. If I call it, onMouseOver="changebox('div3')", the argument makes it to the function when I mouse over the cell. If I uncomment the document.write(cell) statement, in this instance, it prints div3 to the screen. So... why isn't it making any changes to the content of the div3 cell?
function changebox() {
for (var i = 0; i < arguments.length; i++) {
var cell = document.getElementById(arguments[i]).id;
var text = "";
if (cell == 'div3') {
text = "Reduced Travel";
} else if (cell == 'div4') {
text = "Reduced Cost";
}
//document.write(cell)
cell.innerHTML = text;
}
}
In your code cell is a string which holds the id of the object. Update the code as follows
function changebox() {
for (var i = 0; i < arguments.length; i++) {
var cell = document.getElementById(arguments[i]),
text = "";
if (cell.id == 'div3') {
text = "Reduced Travel";
} else if (cell.id == 'div4') {
text = "Reduced Cost";
}
//document.write(cell)
cell.innerHTML = text;
}
}
UPDATE :
You can reduce the code as #Tushar suggested.
No need of iterating over arguments(assuming there are only two elements, but can be modified for more elements).
function changebox() {
// As arguments is not real array, need to use call
// Check if div is present in the arguments array
var div3Index = [].indexOf.call(arguments, 'div3') > -1,
div4Index = [].indexOf.call(arguments, 'div4') > -1;
// If present then update the innerHTML of it accordingly
if (div3Index) {
document.getElementById('div3').innerHTML = 'Reduced Travel';
} else if (div4Index) {
document.getElementById('div4').innerHTML = 'Reduced Cost';
}
}
function changebox() {
var args = [].slice.call(arguments);
args.map(document.getElementById.bind(document)).forEach(setElement);
}
function setElement(ele) {
if (ele.id === 'div3') {
ele.innerHTML = "Reduced Travel";
} else if (ele.id === 'div4') {
ele.innerHTML = "Reduced Cost";
}
}
this make your function easy to be tested
As your assigning the cell variable the id of the element and changing the innerHTML of cell which is not valid .
var changeText = function() {
console.log("in change text");
for(var i= 0; i<arguments.length; i++) {
var elem = document.getElementById(arguments[i]);
var cell = document.getElementById(arguments[i]).id;
var text = "";
console.log(cell)
if (cell === "div-1") {
text = cell+" was selected!!";
} else if(cell === "div-3") {
text = cell+" was selected!!";
} else {
text = cell+" was selected";
}
elem.innerHTML = text;
}
}
This would properly change the text of div mouseovered!!

onchange happen even click on white space of selectbox

I am just trying to add and remove selectbox items using below code,
$('#moveforzero').val("0");
$('#SelectFeatures').change(function() {
var oSrc = document.getElementById('SelectFeatures');
var oDest = document.getElementById('SelectedFeatures');
var zero = document.getElementsByName('moveforzero')[0].value;
for (var i = 0; i < oSrc.options.length; i++) {
var j=parseInt(zero);
if (oSrc.options[i].selected == true) {
oSrc.options[i].disabled=true;
var NewOption = new Option();
//var selected = oSrc.options[i].value;
NewOption.text = oSrc.options[oSrc.options.selectedIndex].text;
NewOption.value = oSrc.options[oSrc.options.selectedIndex].value;
oDest.options[j] = NewOption;
document.getElementsByName('moveforzero')[0].value=j+1;
}
}
});
$('#SelectedFeatures').change(function(){
var d,f;
var minuone=document.getElementsByName('moveforzero')[0].value;
if(parseInt(minuone)>0)
{
document.getElementsByName('moveforzero')[0].value=parseInt(minuone)-1;
}
else
{
document.getElementsByName('moveforzero')[0].value="0";
}
d=$("#SelectedFeatures option:selected").text();
var len=$("#SelectedFeatures").length;
var g =$("#SelectedFeatures");
//d=selectbox.options[(selectbox.selectedIndex)].text;
var oSrc = document.getElementById('SelectFeatures');
for (var i = 0; i < oSrc.options.length; i++) {
if (oSrc.options[i].disabled==true) {
f=oSrc.options[i].text;
if(d==f)
{
oSrc.options[i].disabled=false;
for(var i = 0; i <len; i++)
{
if($("#SelectedFeatures option["+i+"].selected"))
{
jQuery("#SelectedFeatures option[value='"+d+"']").remove();
}
}
}
}
}
});
My problem is even items removing when click on white space inside the removing selectbox.
check my fiddle :http://jsfiddle.net/Manivasagam/ff5Lp0gv/18/
How to fix this?
As per my understanding, you want to remove option when you select it. Here i solve this using delegate method. refer this JSfIDDLE
$('#SelectedFeatures').delegate('option:selected', 'click',function(){
var d,f;
var minuone=document.getElementsByName('moveforzero')[0].value;
if(parseInt(minuone)>0)
{
document.getElementsByName('moveforzero')[0].value=parseInt(minuone)-1;
}
else
{
document.getElementsByName('moveforzero')[0].value="0";
}
d=$("#SelectedFeatures option:selected").text();
var len=$("#SelectedFeatures").length;
//alert(len);
var g =$("#SelectedFeatures");
//alert(d);
//d=selectbox.options[(selectbox.selectedIndex)].text;
var oSrc = document.getElementById('SelectFeatures');
for (var i = 0; i < oSrc.options.length; i++) {
if (oSrc.options[i].disabled==true) {
f=oSrc.options[i].text;
//alert(f);
if(d==f)
{
//alert("if");
oSrc.options[i].disabled=false;
for(var i = 0; i <len; i++)
{
//alert('for');
if($("#SelectedFeatures option["+i+"].selected"))
{
//alert("remove");
jQuery("#SelectedFeatures option[value='"+d+"']").remove();
}
// if(selectbox.options[i].selected)
//selectbox.remove(i);
}
}
}
}
});
How about:
option {
display: inline;
}
option:after {
content: "\A";
white-space: pre;
}
See this updated fiddle.
This is a version of the solution by #Ferret:
Add a blank <option></option> to the end of your select tag and then change the style of the last (blank) option like so:
option:last-child {
display:inline;
padding:0px;
}
You may want to change the style to only apply to that particular select's last item.
Here's the JSFiddle

Is it really necessary to use array, to display an innerHTML of a complete node list after child remove?

This code works well but when I start to remove nodes the complete list disappear and I'm left with one node in the innerHTML, instead of removing one by one gradually which is what I want. To leave a few to none behind perhaps gradually instead of straight one for all displayed in the innerHTML, of the div that displays the removal sort of say... I can perfectly do this to work using arrays but I'm curious if there's an way out without using any(arrays)?
HTML code
<button onClick="remov()">remove</button>
<button onClick="addDiv()">Add Div</button>
<div>
<div></div>
<div></div><div></div>
<div></div>
</div>
<div id="tt"></div>
Javascript Code
var stage = document.getElementsByTagName("div")[0];
var tt = document.getElementById("tt");
function remov() {
if (stage.hasChildNodes()) {
stage.removeChild(stage.firstChild);
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML = stage.childNodes[i].nodeName;
}
if (!stage.hasChildNodes()) {
tt.innerHTML = "no nodes";
}
}
}
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML += stage.childNodes[i].nodeName;
}
function addDiv() {
var a = document.createElement("div");
stage.appendChild(a);
if (!stage.hasChildNodes()) {
tt.innerHTML += stage.firstChild.nodeName;
} else {
tt.innerHTML += stage.lastChild.nodeName
}
}
jsfiddle
If you want to display all divs during their removal need to change = to += as below
function remov() {
tt.innerHTML=''; //EDIT forgot to add in this line
if (stage.hasChildNodes()) {
stage.removeChild(stage.firstChild);
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML += stage.childNodes[i].nodeName; //<------- + needed to display all divs
}
if (!stage.hasChildNodes()) {
tt.innerHTML = "no nodes";
}
}
}
EDIT Fiddle added

JavaScript make specific letter a different color?

I am trying to make a specific letter: "*" be red in a line of JavaScript coding that I am working with.
The following is my original:
function init(){
var inp = document.getElementsByTagName('input');
for(var i = 0; i < inp.length; i++) {
if(inp[i].type == 'text','tel','number', 'email') {
inp[i].setAttribute('rel',inp[i].defaultValue)
inp[i].setAttribute('style', 'color: grey;')
inp[i].onfocus = function() {
if(this.value == this.getAttribute('rel')) {
this.value = '';
this.setAttribute('style', 'color: black;')
} else {
return false;
}
}
In order to make a specific letter red, would I change it to?
function init(){
var inp = document.getElementsByTagName('input');
for(var i = 0; i < inp.length; i++) {
if(inp[i].type == 'text','tel','number', 'email') {
inp[i].setAttribute('rel',inp[i].defaultValue)
inp[i].setAttribute('style', 'color: grey;')
inp[i].onfocus = function() {
if(this.value == this.getAttribute('rel')) {
this.value = '';
this.setAttribute('style', 'color: black;')
if(this.value == this.getAttribute('*')) {
this.setAttribute('style', 'color: red;')
} else {
return false;
}
}
How would I achieve this?
... because I am really bored, I ended up doing what you wanted using javascript.
It uses Mootools, but it should provide enough inspiration for you to recreate it using jQuery if you so desire.
function reposition() {
var position = inputEl.getPosition();
var occludeLabel = inputEl.value;
occludeLabel = occludeLabel.replace(/\*/g, '<span class="red">*</span>', 'g');
occludeEl.setStyles({
top: position.y + 1,
left: position.x + 1
});
occludeEl.set('html', occludeLabel);
}
Basically, every time you blur the input, a div containing the input box's value is placed over the input box, occluding the text. I ran a simple .replace() to replace all asterisks with a span that would turn its contents red.
Please see this jsfiddle for all of the code: http://jsfiddle.net/eTEvQ/2/
You can style only the elements but not the attributes..
This line does not make any sense..
this.value == this.getAttribute('*')
* is not a valid attribute name
Also this here is the current input element in Question..
You can set a color for the input element as a whole but not for specific characters inside them

Categories