How to wrap code in a function correctly? - javascript

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

Related

Autodesk forge viewer table row click to isolate elements

I am trying to create a dynamic table inside the viewer's page.
each row of the table represents an object from the model and has a couple of different parameters ( name, level, etc..)
I want to make a click event on each row, that isolates the element in the viewer's model.
I have created the table programmatically using js. (the table is created after pressing an external command button )
how can I add an event listener to a row click, that would isolate the element?
this is my code for creating the table after pressing the command button:
var myTable = $('.my-table');
var myArr = rows; //matrix of object values
for (var i = 0; i < myArr.length; i++)
myTable.append("<tr id=" + i + ">" +
" <td>" + myArr[i][0] + "</td>" +
"<td>" + myArr[i][1] + "</td>" +
"<td>" + myArr[i][2] + "</td>" +
"<td>" + myArr[i][3] + "</td>" +
"<td>" + myArr[i][4] + "</td>" +
"<td>" + myArr[i][5] + "</td>" +
"<td>" + myArr[i][6] + "</td>" +
"<td id=" + "tt" + ">" + myArr[i][7] + "</td>" +
"</tr>");
const row = document.getElementById(`${i}`);
row.addEventListener('onClick', function(evt, item) { /// we are using a viewer api property to isolate the
_this.viewer.isolate(_this.modelData.getIds(myArrNames[i][1], item[0]._model.label));
});
First, it's not a Forge issue but a JavaScript syntax and indent issue.
After re-indenting your code, you can see the codes for adding the click event is out of the for-loop, so you need to add the bracket pair to include the codes for adding the click event into the for-loop.
When defining for-loop in JavsScirpt without bracket { and }, it only takes the first line in the count.
In addition, there is no onClick event. When using addEventListener, the event name is click, not onClick.
var myTable = $('.my-table');
var myArr = [[1,2,3,4,5,6,7], [1,2,3,4,5,6,7]]; //matrix of object values
for (var i = 0; i < myArr.length; i++) {
myTable.append("<tr id=" + i + ">" +
" <td>" + myArr[i][0] + "</td>" +
"<td>" + myArr[i][1] + "</td>" +
"<td>" + myArr[i][2] + "</td>" +
"<td>" + myArr[i][3] + "</td>" +
"<td>" + myArr[i][4] + "</td>" +
"<td>" + myArr[i][5] + "</td>" +
"<td>" + myArr[i][6] + "</td>" +
"<td id=" + "tt" + ">" + myArr[i][7] + "</td>" +
"</tr>");
const row = document.getElementById(`${i}`);
row.addEventListener('click', function(evt) { /// we are using a viewer api property to isolate the
_this.viewer.isolate(_this.modelData.getIds(myArrNames[i][1], item[0]._model.label));
});
}
To use onClick, it will become:
const row = document.getElementById(`${i}`);
row.onClick = function(evt) { /// we are using a viewer api property to isolate the
_this.viewer.isolate(_this.modelData.getIds(myArrNames[i][1], item[0]._model.label));
});
Lastly, why not just use jQuery only? The jquey.on can help bind events to dynamically created items, so that the click event will be delegated to any tr element in the table, even if it's added after you bound the event handler.
var myTable = $('.my-table');
var myArr = [[1,2,3,4,5,6,7], [1,2,3,4,5,6,7]]; //matrix of object values
myTable.on('click', 'tr', function() {
_this.viewer.isolate(_this.modelData.getIds(myArrNames[i][1], item[0]._model.label));
});
for (var i = 0; i < myArr.length; i++) {
myTable.append("<tr id=" + i + ">" +
" <td>" + myArr[i][0] + "</td>" +
"<td>" + myArr[i][1] + "</td>" +
"<td>" + myArr[i][2] + "</td>" +
"<td>" + myArr[i][3] + "</td>" +
"<td>" + myArr[i][4] + "</td>" +
"<td>" + myArr[i][5] + "</td>" +
"<td>" + myArr[i][6] + "</td>" +
"<td id=" + "tt" + ">" + myArr[i][7] + "</td>" +
"</tr>");
}
ref: https://stackoverflow.com/a/15420578

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");

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>";

Javascript Append Function, Need to build a loop

I have a .php file where I am using both HTML and JavaScript to display items from my database. I have a JavaScript append function that is creating cards where each item is display. On my cards, I have a button that will expand the card to show product history. Some products have more history than others so the expansion needs to be dynamic. The historical data is being pulled from database and is initially in a php array. I originally was going to institute php into the javascript append function but I could not figure out how to set the JavaScript index variable 'I' to my php index. So I want to just stay with JavaScript. But I don't know how to write a loop in the middle of this append function that will loop through the historical array and populate the expansion. Below is what I am attempting. I took out a lot of the lines in the append function but you can see what I am trying to do.
function get_products() {
clear_cards();
$.each(productNumbers,
function(i, value) {
$('.main_card_shell').append(
"<div class='card_content card_style' id='card" + i + "'>" +
"<div id='card_tab2" + i + "' class='tabcontent' data-tab='tab-name2'>" +
"<div class='details_tables'>" +
"<table>" +
"<tr>" +
"<th>Item Type</th>" +
"<th>Painted</th>" +
"<th>Last Sold" +
"<a id='_close_tab" + i + "' class='tablinks tab_override' onclick=\"openCity(event,'card_tab4" + i + "')\">" +
"<i class='large angle up icon'></i>" +
"</a>" +
"</th>" +
"</tr>" +
"<tr>" +
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength)
{
+ "<td>" + itemtypesplit[counter] + "</td>" +
+ "<td>" + itemdatesplit[counter] + "</td>" +
counter = counter + 1;
}
+
"</tr>" +
"</table>" +
"</div>" +
"</div>" +
Please help. I had it working with PHP inserted in, but I just couldn't figure out how to set it to a PHP variable.
Place this code into a function:
function getSomething(i) {
var html = '';
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength) {
html += "<td>" + itemtypesplit[counter] + "</td>";
html += "<td>" + itemdatesplit[counter] + "</td>";
counter = counter + 1;
}
return html;
}
And then use it in your HTML building block:
'<some html>' + getSomething(i) + '<some other html>'

Trying to store the response of ajax to a global variable but that value is not assigned outside the ajax code

One more thing is here that if I use the alert() at end of the ajax code the code is working fine. here whatever the ajax response comes has to be appended to the existing table.
for (var i = 1; i < rows.length; i++) {
var cells = splitCSVtoCells(rows[i], ",");
var obj = {};
for (var j = 0; j < cells.length; j++) {
obj[first_Row_Cells[j]] = cells[j];
}
jsonArray.push(obj);
}
console.log(jsonArray);for (var i = 0; i < jsonArray.length-1; i++) {
html += "<tr id=\"rowitem" + i + "\"><td id=\"rownum"+i+ "\" style=\"display:none;\">" + i + "</td><td> " + jsonArray[i].Clientgroup + " </td>";
html += "<td>" + jsonArray[i].hostgroup + "</td>";
html += "<td>" + jsonArray[i].server + "</td>";
html += "<td>" + jsonArray[i].Group + "</td>";
html += "<td>" + jsonArray[i].user + "</td>";
html += "<td>" + jsonArray[i].ticket + "</td>";
html += "<td>" + jsonArray[i].requesttype + "</td>";
$.ajax({
url : "BulkValidateServlet",
type : "POST",
data : {clientgroup: jsonArray[i].Clientgroup, hostgroup: jsonArray[i].hostgroup, server: jsonArray[i].server
},success : function(response){
//alert("i in of ajax:"+i);
status = response;
if (status) {
//alert("outside if: " + status);
//$('<img src=\'images/check_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/check_mark.png' height='20' width='20'/></td>";
} else {
//alert("outside else: " + status);
//$('<img src=\'images/cross_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/cross_mark.png' height='20' width='20'/></td>";
}
console.log("Data: " + status);
// alert("Data: " + status );
//return status;
}
});
console.log("outside: " + status);
alert();
}
document.getElementById('tbodyLeads').innerHTML = html;
}
You can try adding
async: false
to your ajax attributes.
Refer to this link.

Categories