Image does not appear on div even though div class changes - javascript

I am trying to show an animation on .gif format, before the page loads JSON data on the div. But It does not show gif.
I check in the console if it does not change the class, but it changes.
Basically code should work like this:
1- Press Button
2- Load image (css class: "loading")
3- Start json call (It takes around 8 secs)
4- Load table (css class: "loaded")
HTML and javascript are in seperate files
gif animation loads when I change the classes into the opposite. But this time it loads on the json table data.
CSS:
div.loading {
width: 600px;
height: 600px;
background: #FFF url('loading.gif') no-repeat 50% 50%;
}
div.loaded {
width: 600px;
height: 600px;
}
Javascript:
function loadOutputs() {
console.log(document.getElementById('loadingElement').className);
document.getElementById("loadingElement").className = "loading";
console.log(document.getElementById('loadingElement').className);
makeProxyCall(
"http://localhost:9090/myService/tool/runTool?tool=myTool",
function(data) {
var globalCounter = 0;
var tbody = document.getElementById('tbody');
var trheader = "<tr><td>Name</td><td>Value</td><td>Type</td><td>UnitOfMeasure</td><td>Mode</td></tr>"
tbody.innerHTML = trheader;
for ( var i = 0; i < 10; i++) {
var tr = "<tr>";
//if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) obj[i].value += "0";
tr += "<td>" + data[0][i].name + "</td>" + "<td>"
+ data[0][i].value + "</td>" + "<td>"
+ data[0][i].type + "</td>" + "<td>"
+ data[0][i].unitOfMeasure + "</td>" + "<td>"
+ data[0][i].mode + "</td></tr>";
tbody.innerHTML += tr;
}
});
document.getElementById("loadingElement").className = "loaded";
console.log(document.getElementById('loadingElement').className);
}
HTML:
<div id="loadingElement" class="loaded">
<button type="button" class="btn-blue"
style="top: 80px; right: 130px;" onclick="loadOutputs()">Load
Outputs</button>
<table>
<tbody id="tbody"></tbody>
</table>
</div>

The javascript is executed asynchronously. The classname 'loaded' is set before makeproxycall is finished.
Add the classname switch to the end of the callback function in makeproxycall:
makeProxyCall(
"http://localhost:9090/myService/tool/runTool?tool=myTool",
function(data) {
var globalCounter = 0;
var tbody = document.getElementById('tbody');
var trheader = "<tr><td>Name</td><td>Value</td><td>Type</td><td>UnitOfMeasure</td><td>Mode</td></tr>"
tbody.innerHTML = trheader;
for ( var i = 0; i < 10; i++) {
var tr = "<tr>";
//if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) obj[i].value += "0";
tr += "<td>" + data[0][i].name + "</td>" + "<td>"
+ data[0][i].value + "</td>" + "<td>"
+ data[0][i].type + "</td>" + "<td>"
+ data[0][i].unitOfMeasure + "</td>" + "<td>"
+ data[0][i].mode + "</td></tr>";
tbody.innerHTML += tr;
}
document.getElementById("loadingElement").className = "loaded";
});

Related

How to delete rows other than a random row on a table(Javascript)?

I get data from the user and put it into the table by collating, I want to show a random line from the table I want to delete the other rows
function bilgi(){
var random = Math.floor(Math.random() * (allobjs.length - 1) ) + 1;
if (allobjs[random].id != 'blank'){
allobjs[random].animate({fill: 'rgb(19, 167, 236)'}, 1000);
$(function() {
$.getJSON('/static/yer.json', function(data) {
var deger = $("input[name=deger]").val()
var al = deger.split(",")
$.each(data, function(i, f) {
if(f.plaka == random){
var tblRow = "<tr>" +
"<td>" + "<img class='aaa'src='/static/bayrak.jpg' alt='' />" + "</td>" +
"<td>" + deger + "</td>" +
"<td>" + f.yerler + "</td>" +
"<td>" + f.bolge + "</td>" +
"<td>" + f.ili + "</td>" +
"<td>" + f.teskilati + "</td>" +
"<td>" + f.acm + "</td>" +
"</tr>"
$("tbody").append(tblRow);
}
});
$("tbody tr").hide()
var toplam= $("tbody tr").size()
ratgel=Math.floor(Math.random() * toplam);
$("tbody tr").eq(ratgel).show(1000)
});
});
}}
In javascript add class NOSHOW to each tr you want to hide Then using css .NOSHOW{display:none;} If you want a complete solution show your html.
something like the following might work:
At the start of your function add the following:
var tr = getElementsByTagName('tr');
for(var i = 0; i < tr.length;i++){
tr[i].className += "noshow";
}
then in you html add:
<style>
.noshow{
display:none;
}
</style>
This should work as you then append the row you want to the end of the table.
Later, when you want to display the entire table again you can use:
element.classList.remove("noshow");

How to pass paramters in dynamically created functions in Javascript?

I have created one form and form after submitting the value I want to show them in a table. In table I have one section where I want to delete or edit a particular user on a button. But when I am passing the id to that function I am getting error saying that refernece error occurred!
function getEmployeeDetails() {
for (var i = 0; i < userArray.length; i++) {
var tr = "<tr>";
tr +=
"<td class='table-data'/td>" +
userArray[i].id +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].name +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].email +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].gender +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].role +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].english +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].hindi +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].othersLang +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].description +
"</td>" +
"<td class='table-data'/td>" +
"<button onclick='deleteUser( userArray[i].id )'>Delete</button> || <button onclick='editUser( userArray[i].id )'>Edit</button>" +
"</td>" +
"</tr>";
tbody.innerHTML += tr;
}
}
function deleteUser(id) {
console.log("delteuser", typeof id, id);
}
function editUser(id) {
console.log("edit", id);
}
Where I have made the mistakes?
The problem is in the string concatenation you are using in the onClick event.
You can use a backtick character instead.
Copy-paste and check the below code.
<html>
<body>
<table id="table"></table>
<script>
getEmployeeDetails();
function getEmployeeDetails() {
let userArray = [{ id: 1 }, { id: 2 }];
var tr = "";
for (var i = 0; i < userArray.length; i++) {
tr +=
`<td class="table-data">
<button onclick="deleteUser(` +
userArray[i].id +
`)">Delete</button> || <button onclick="editUser( ` +
userArray[i].id +
`)">Edit</button>
</td>`;
}
document.getElementById("table").innerHTML = tr;
}
function deleteUser(id) {
console.log("delteuser", typeof id, id);
}
function editUser(id) {
console.log("edit", id);
}
</script>
</body>
</html>
Change
<button onclick='deleteUser( userArray[i].id )'>
To something like
<button onclick='deleteUser('+userArray[i].id+')'>
In your current attempt you are not inserting the value of userArray[i].id but the variable userArray[i].id which is kind of nonsense.
Same story with the editUser function

Modify function to make names also links

I have a function that creates a table that consists of several elements all of which are taken from a saved file. The table has other information inside(url) Inside the table surname name and middle name(if exists) is put under one header "Full name". How can I modify this function so that it not only displays the name but makes it so that the name is also a url link?
var members = data.results[0].members;
createTable(members)
function createTable(members) {
var table = "";
var cols = 1;
var rows = members.length;
for (var r = 0; r < rows; r++) {
table += "<tr>";
for (var c = 0; c < cols; c++) {
table +=
"<td>" + members[r].first_name +", "+
(members[r].middle_name || " ") +" "+
members[r].last_name + "</td>";
table += "<td>" + members[r].party + "</td>" + "<td>" + members[r].state + "</td>" + "<td>" + members[r].seniority + "</td>";
if (members[r].votes_with_party_pct === undefined) {
table += "<td>" + "-" + "</td>"
} else {
table += "<td>" + members[r].votes_with_party_pct + "%" + "</td>"
}
}
table += "<tr>";
}
document.getElementById("house-data").innerHTML = JSON.stringify(table);
}
function createTable(members) {
var table = "";
var cols = 1;
var rows = members.length;
for (var r = 0; r < rows; r++) {
table += "<tr>";
for (var c = 0; c < cols; c++) {
table +=
"<td><a href=\"YOUR_LINK_HERE\">" + members[r].first_name +", "+
(members[r].middle_name || " ") +" "+
members[r].last_name + "</a></td>";
...
Replace YOUR_LINK_HERE with the URL you want.
If you want to use a variable, use:
table +=
"<td><a href=\""+url+"\">" + members[r].first_name +", "+
(members[r].middle_name || " ") +" "+
members[r].last_name + "</a></td>";

How to wrap code in a function correctly?

I have a code that automatically creates a table for me. It gathers information from a saved file, however, I have two of these files and currently can call one at the time. How can I possibly wrap this code in a function so that there are two calls on the same code with different information that will be put in it? So right now I am using getElementById on file "house-data" but I also want to have this same js on a file "senate-data"
I thought of creating some sort of if statement where if(you have one file): do this
else
do that. But this method doesnt work.
var table = "";
var cols = 1;
var members = data.results[0].members;
var rows = members.length;
table += "<tr>" +
"<th>" + "Full Name" + "</th>" +
"<th>" + "Party" + "</th>" +
"<th>" + "State" + "</th>" +
"<th>" + "Seniority"+ "</th>" +
"<th>" + "Total Votes"+ "</th>" + "</tr>";
for (var r = 0; r < rows; r++) {
table += "<tr>";
for (var c = 0; c < cols; c++) {
table +=
"<td>" + members[r].first_name +", "+
(members[r].middle_name || " ") +" "+
members[r].last_name + "</td>";
table += "<td>" + members[r].party + "</td>" + "<td>" + members[r].state + "</td>" + "<td>" + members[r].seniority + "</td>";
if (members[r].votes_with_party_pct === undefined) {
table += "<td>" + "-" + "</td>"
} else {
table += "<td>" + members[r].votes_with_party_pct + "%" + "</td>"
}
}
table += "<tr>";
}
document.getElementById("house-data").innerHTML = JSON.stringify(table);
function tableCreator(elementID, data) {
[...]
document.getElementById(elementID)[...]
}
above will work for you and keep in mind to check
var members = data.results[0].members;
is available before going to for loop

Working with JSON input

I'm trying to get a JSON input with AJAX and load it in a select control.
but when I run it :\ It stuck on "Downloading the recipes....".
anyone see the problem maybe? (I tried couple of changes but nothing work so far)
1 more issue can anyone think on a shorter way to do the
ConvertToTable(targetNode)
cuse it's way to long and complex, I think :\
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
document.getElementById("span").style.visibility = "visible";
document.getElementById("span1").style.visibility = "hidden";
document.getElementById("button").style.visibility = "hidden";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
result = xmlhttp.responseText;
result = eval('(' + result + ')');
txt = "<select onchange='ShowRecipeDetails(this)'>";
for (i = 0; i < result.length; i++) {
txt = txt + "<option VALUE=" + result[i].recipe + ">" + result[i].recipe + "</option>";
}
txt = txt + "</select >";
document.getElementById("span").style.visibility = "hidden";
document.getElementById("span1").style.visibility = "visible";
document.getElementById("myDiv").innerHTML = txt;
}
}
xmlhttp.open("POST", "http://food.cs50.net/api/1.3/menus?meal=BREAKFAST&sdt=2011-03-21&output=json", true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.send();
}
function ShowRecipeDetails(event) {
// get the index of the selected option
var idx = event.selectedIndex;
// get the value of the selected option
var field = event.options[idx].value;
$.ajax({
type: "GET",
url: "http://food.cs50.net/api/1.3/recipes?&output=json&id=" + field,
success: function (data) {
$("#TableDiv").html(ConvertToTable(data[0]));
}
});
}
function ConvertToTable(targetNode) {
var table = "<table border = 1 borderColor =green>";
table += "<tr>";
table += "<td>" + "ID" + "</td>";
table += "<td>" + targetNode.id + "</td>";
table += "</tr>";
table += "<td>" + "Ingredients:" + "</td>";
table += "<td>" + targetNode.ingredients + "</td>";
table += "</tr>";
table += "<td>" + "Name:" + "</td>";
table += "<td>" + targetNode.name + "</td>";
table += "</tr>";
table += "<td>" + "Size:" + "</td>";
table += "<td>" + targetNode.size + "</td>";
table += "</tr>";
table += "<td>" + "Unit" + "</td>";
table += "<td>" + targetNode.unit + "</td>";
table += "</tr>";
table += "<td>" + "VEGETARIAN:" + "</td>";
table += "<td>" + targetNode.VEGETARIAN + "</td>";
table += "</tr>";
table += "</tr>";
table += "</table>"
return table;
}
</script>
and the HTML:
<button id="button" type="button" onclick="loadXMLDoc()" >Get all recipes</button>
<br />
<span id="span" style="visibility:hidden">Downloading the recipes....</span>
<span id="span1" style="visibility:hidden">Please choose a recipe ID to view</span>
<div id="jsonDiv"></div>
<div id="myDiv"></div>
<div id="TableDiv"></div>
The HarvardFood API also supplies a JSONP version. So if you change your URL to this:
http://food.cs50.net/api/1.3/menus?meal=BREAKFAST&sdt=2011-03-21&output=jsonp&callback=parseResponse
you can create a parseResponse function to handle the data that comes back, and you can do the AJAX by inserting a script tag.
The problem is that you're running afoul the Same Origin Policy.
I see that you've updated the question to use jQuery AJAX. That offers a jsonp data type, which might be easier than adding a script tag.

Categories