How can I add a header to my JSON output table? - javascript

I'm trying to add a header to this JSON output table, but I have no clue how to do that. This code gives me a table populated with the data returned from the database and puts it in a table format as structured by the <td><tr> tags. The problem is that I need a header for the table and I don't know how to get that part coded. Any ideas?
function renderSearchResults( results, domNode ) {
var i;
var out = "<table>";
if (results.length === 0) {
domNode.innerHTML = 'No results matching your search.';
return;
}
// loop to print the JSON in a table format
results.forEach(function (result) {
console.info(result);
out += "<tr><td>" +
result.ContractId +
"</td><td>" +
result.ContractTitle +
"</td><td>" +
result.Terminal +
"</td><td>" +
result.Cabinet +
"</td><td>" +
result.Section +
"</td><td>" +
result.Folder +
"</td><td>" +
result.Sheet +
"</td><td>" +
result.Consult +
"</td><td>" +
result.Location +
"</td><td>" +
result.Active +
"</td><td>" +
result.Theme +
"</td><td>" +
result.Construction +
"</td><td>" +
result.Subtheme +
"</td><td>" +
result.AsBuilt +
"</td><td>" +
result.Year +
"</td><td>" +
"<a href= " + result.Path + " target=_blank>" + "Binder" + "</a>"
} );
out += "</table>";
domNode.innerHTML = out;
}

During your initial declaration of out you can put in <th> or tableheader tags, i.e:
function renderSearchResults( results, domNode ) {
var i;
var out = "<table><th>ContractId</th><th>ContractTitle</th><th>Terminal</th><th>Cabinet </th><th>Section </th><th>Folder </th><th>Sheet </th><th>Consult </th><th>Location </th><th>Active </th><th>Theme </th><th>Construction </th><th>Subtheme </th><th>AsBuilt </th><th>Year </th>";
if (results.length === 0) {
domNode.innerHTML = 'No results matching your search.';
return;
}
results.forEach(function (result) {
console.info(result);
out += "<tr><td>" +
(result.ContractId !== null ? result.ContractId : 'Not Applicable') +
"</td><td>" +
(result.ContractTitle !== null ? result.ContractTitle : 'Not Applicable') +
"</td><td>" +
(result.Terminal !== null ? result.Terminal : 'Not Applicable') +
"</td><td>" +
(result.Cabinet !== null ? result.Cabinet : 'Not Applicable') +
"</td><td>" +
(result.Section !== null ? result.Section : 'Not Applicable') +
"</td><td>" +
(result.Folder !== null ? result.Folder : 'Not Applicable') +
"</td><td>" +
(result.Sheet !== null ? result.Sheet : 'Not Applicable') +
"</td><td>" +
(result.Consult !== null ? result.Consult : 'Not Applicable') +
"</td><td>" +
(result.Location !== null ? result.Location : 'Not Applicable') +
"</td><td>" +
(result.Active !== null ? result.Active : 'Not Applicable') +
"</td><td>" +
(result.Theme !== null ? result.Theme : 'Not Applicable') +
"</td><td>" +
(result.Construction !== null ? result.Construction : 'Not Applicable') +
"</td><td>" +
(result.Subtheme !== null ? result.Subtheme : 'Not Applicable') +
"</td><td>" +
(result.AsBuilt !== null ? result.AsBuilt: 'Not Applicable') +
"</td><td>" +
(result.Year !== null ? result.Year : 'Not Applicable')+
"</td><td>" +
"<a href= " + result.Path + " target=_blank>" + "Binder" + "</a>"
} );
out += "</table>";
console.log(out);
domNode.innerHTML = out;
}

There is a different tag for the table header.
<tr> is for row <th> for your headers and <td> for the data.
You can check here for more info.
You can either add your header after your check for results:
if (results.length === 0) {
domNode.innerHTML = 'No results matching your search.';
return;
} else {
out += "<tr><th>Header</th></tr>"
}

Related

How can I check if key is empty for IF Statement Inside a FOR Loop?

The line in question is...
if(listContent[Source].properties === ""
I need it to check if the "Source" key has any value. It's currently not outputting anything. What is proper syntax for this?
Here is the full code:
if (visibleFeatures) {
var uniqueFeatures = getUniqueFeatures(visibleFeatures, "arrayIndex");
for (var i = 0; i < uniqueFeatures.length; i++) {
if (listContent[Source].properties === "") {
listContent += '<div class="dealer"><h3>' + uniqueFeatures[i].properties.Name + '</h3><p class="address">' + uniqueFeatures[i].properties.Address + '<br>' + uniqueFeatures[i].properties.City + ', ' + uniqueFeatures[i].properties.State + ' ' + uniqueFeatures[i].properties.Zip + '</p><p class="phone">' + uniqueFeatures[i].properties.Phone + '</p></div>';
} else {
listContent += '<div class="dealer"><h3>' + uniqueFeatures[i].properties.Name + '</h3><p class="address">' + uniqueFeatures[i].properties.Address + '<br>' + uniqueFeatures[i].properties.City + ', ' + uniqueFeatures[i].properties.State + ' ' + uniqueFeatures[i].properties.Zip + '</p><p class="phone">' + uniqueFeatures[i].properties.Phone + '</p><p class="bl-map-link">' + uniqueFeatures[i].properties.Source + '</p></div>';
}
}
Thank you guys so much for all the help. I was able to figure out my error.
!!uniqueFeatures[i].properties.Source
The !! is what made the difference. I'm still researching why this works and why this doesn't if (strValue === "").

Function replicating items

The function is replicating each item that I place in. It runs through all of the panels, and places the additional items each time it runs. I have tried using the if statement that is placed but it is not working. I am placing the entire code block, but the issue starts at the let x = -1 variable. The full code block is strictly for reference. Please let me know if there is anything additional that I can provide. Additionally, .first() will not work for this instance.
function getRecordUI( alias, type, id, viewtype, version ) {
// Get record model from Data Model Registry
if ( type ) {
getJSONUIModel( type,
function ( data ) {
displayRecordSections( alias, type, id, version, viewtype, data );
},
function (error) {
console.log("Error getting UI model for type " + type);
console.log(error);
displayRecordSections( alias, type, id, version, viewtype, null );
});
} else {
displayRecordSections( alias, type, id, version, viewtype, null );
}
let x = -1;
lastName = "";
$("#panels-region .panel-heading").each(function () {
x++
let curName = $(this).attr("name")
if(!$('<a id="panels-sidebar-' + curName.replace(/ |\//g, "_") + '" class="w3-bar-item" href="#panel-' + x + '-header" title="' + curName.replace(/ |\//g, "_") + '"> ' + curName + '</a>')) {
$('<a id="panels-sidebar-' + curName.replace(/ |\//g, "_") + '" class="w3-bar-item" href="#panel-' + x + '-header" title="' + curName.replace(/ |\//g, "_") + '"> ' + curName + '</a>').insertAfter("#panels-sidebar" + lastName.replace(/ |\//g, "_"))
break;
}
lastName = "-" + curName;
});
$("#graph-region .panel-heading h4").each(function () {
x++
let curName = $(this).text().replace("Collapse panelExpand panel", "")
if(!$('<a id="tree_viewers-sidebar-' + curName.replace(/ |\//g, "_") + '" class="w3-bar-item" href="#panel-' + x + '-header" title="' + curName.replace(/ |\//g, "_") + '"> ' + curName + '</a>')) {
$('<a id="tree_viewers-sidebar-' + curName.replace(/ |\//g, "_") + '" class="w3-bar-item" href="#panel-' + x + '-header" title="' + curName.replace(/ |\//g, "_") + '"> ' + curName + '</a>').insertAfter("#tree_viewers-sidebar" + lastName.replace(/ |\//g, "_"))
break;
}
lastName = "-" + curName
});
$(".menu-links a").css("padding", "0px 8px")
$(".panel-body").css("background-color", "white")
$("#panels-region .panel-wrapper .panel-default").css("background-color", "white")
}

Print ".00" When The Result Is A Whole Number?

I want to try and print ".00" after the variables cache.todayHigh and cache.todayLow are whole numbers.
if (ddimgtooltip.showTips) {
// update tooltip
tip = 'High ' + strings.baro_info + ': ' + cache.todayHigh + ' ' + data.pressunit + ' ' + strings.at + ' ' + data.TpressTH +
' <br> ' + strings.minimum_info + ' ' + strings.baro_info + ': ' + cache.todayLow + ' ' + data.pressunit + ' ' + strings.at + ' ' + data.TpressTL;
if (cache.trendVal !== -9999) {
tip += '<br>' + strings.baro_trend_info + ': ' + baroTrend(cache.trendVal, data.pressunit, true) + ' ' +
(cache.trendValRnd > 0 ? '' : '') + cache.trendValRnd + ' ' + data.pressunit + '/hr';
}
$('#imgtip5_txt').html(tip);
}
e.g. 1017 hPa to 1017.00 hPa.
Is this possible?
Thanks,
William
Try this,
var yvalue = '1702 hpa';
var num = yvalue.replace(/[^0-9]+/ig,"");
value = Number(num).toFixed(2);
var fvalue= value +' '+yvalue.split(' ')[1]
console.log(fvalue);

Function in JavaScript that outputs concat url to YUI Chart Library Output

Trying to properly write a function in JavaScript that outputs a concat'd url to Chart Library Output (for chart re-rendering)... based on selected options in dropdown list.
Problem: I am not getting the chart to re-render with the concatenated url (which should be sent each time an option is selected in the dropdown).
JavaScript code in head:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest(); // instantiate request
xmlHttp.open( "GET", theUrl, false ); // open url
xmlHttp.send( null ); // sending nothing
return xmlHttp.responseText; // return url's data as text
};
function selectFabric(){
var urlString = "http://localhost:8083/tbl/sparqlmotion?id=LiabilityChart&arg1=";
var fabrics = document.getElementById('fabrics');
var selectedFabric = fabrics.options[fabrics.selectedIndex];
var linkAddTogether = [urlString + selectedFabric.value];
var linkResult = linkAddTogether[0];
var result = httpGet(linkResult);
if (selectedFabric.value != "nothing"){
return linkResult; // update begins // document.write(linkAddTogether)
};
};
function revive (key, value) {
if (value.datatype == "http://www.w3.org/2001/XMLSchema#double" || // if datatype is this
value.datatype == "http://www.w3.org/2001/XMLSchema#integer" || // or, this
value.datatype == "http://www.w3.org/2001/XMLSchema#float") // or, this
{
return (parseInt(value.value)) // if '#double', '#integer', or '#schema', then: 'vars' label + convert the datatype's float value to integer
}
else if (value.type == 'literal')
{
return (value.value) // if datatype's value is a literal: 'vars' label + return as a string
}
else if (value.datatype == 'http://www.w3.org/2001/XMLSchema#date')
{
return value.value // if "XMLSchema#date's" value is a literal: 'vars' label + return as a string
}
else
{
return value // if datatype is anything else: 'vars' label + return value as a string
}
};
var scriptHead = ["YUI().use('charts',function(Y){var myDataValues=\n\n["];
var scriptTail = ["\n];\n\nvar styleDef={series:{Stock:{line:{color:'#EEB647'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Liability:{line:{color:'#171944'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Shipment:{line:{color:'#ff0000',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#ff0000',alpha:0,wmode:'transparent'},over:{fill:{color:'#ff0000',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Production:{line:{color:'#FFD700',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#FFD700',alpha:0,wmode:'transparent'},over:{fill:{color:'#FFD700',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Order:{line:{color:'#006400',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#006400',alpha:0,wmode:'transparent'},over:{fill:{color:'#006400',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}}}};var myAxes={dateRange:{keys:['date'],position:'bottom',type:'category',title:'Date Range',styles:{majorTicks:{display:'none'},label:{rotation:-45,margin:{top:5}},title:{fontSize:'90%'}}}};var mychart=new Y.Chart({dataProvider:myDataValues,interactionType:'planar',render:'#mychart',categoryKey:'Date',styles:styleDef,categoryType:'time',horizontalGridlines:{styles:{line:{color:'#fff'}}},verticalGridlines:{styles:{line:{color:'#fff'}}}})});\n\n"];
var simpleHead = [scriptHead];
var simpleTail = [scriptTail];
var oldData = JSON.parse(result, revive);
HTML code for form (in body):
form style="width:200px; color:#333; padding-right:5px; padding-bottom:2px; padding-left:55px; margin-top:0px; clear:none;" name="properties" id="properties">
select style="width:160px; color:#333; clear:none; display:block;" name="fabrics" id="fabrics" onChange="selectFabric()">
option value="nothing">Select Fabric END option
option value="KOD23-4074-LV">KOD23-4074-LV END option
option value="SGOD2-2858-LV">SGOD2-2858-LV END option
option value="W-897-LV">W-897-LV END option
option value="FF-4084-LV">FF-4084-LV END option
END select
END form
JavaScript code for chart (write script in body to render YUI chart plug-in):
document.write('\x3Cscript type="text/javascript" id="source">');
document.write(simpleHead[0] + '\n{Date: "' + oldData.results.bindings[0].date + '", Liability: ' + oldData.results.bindings[0].liability + ", Stock: " + oldData.results.bindings[0].stock + ", " + oldData.results.bindings[0].event + ": " + oldData.results.bindings[0].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[1].date + '", Liability: ' + oldData.results.bindings[1].liability + ", Stock: " + oldData.results.bindings[1].stock + ", " + oldData.results.bindings[1].event + ": " + oldData.results.bindings[1].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[2].date + '", Liability: ' + oldData.results.bindings[2].liability + ", Stock: " + oldData.results.bindings[2].stock + ", " + oldData.results.bindings[2].event + ": " + oldData.results.bindings[2].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[3].date + '", Liability: ' + oldData.results.bindings[3].liability + ", Stock: " + oldData.results.bindings[3].stock + ", " + oldData.results.bindings[3].event + ": " + oldData.results.bindings[3].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[4].date + '", Liability: ' + oldData.results.bindings[4].liability + ", Stock: " + oldData.results.bindings[4].stock + ", " + oldData.results.bindings[4].event + ": " + oldData.results.bindings[4].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[5].date + '", Liability: ' + oldData.results.bindings[5].liability + ", Stock: " + oldData.results.bindings[5].stock + ", " + oldData.results.bindings[5].event + ": " + oldData.results.bindings[5].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[6].date + '", Liability: ' + oldData.results.bindings[6].liability + ", Stock: " + oldData.results.bindings[6].stock + ", " + oldData.results.bindings[6].event + ": " + oldData.results.bindings[6].current + "}" + simpleTail[0] + "\n\n");
document.write('\x3C/script>');

Problems with a jquery line when using Razor

I have have following line that is working correctly:
html: "<td>" + goalcard.Name + "</td><td>" + goalcard.Customer + "</td><td>" + goalcard.PlannedDate + "</td><td>" + goalcard.CompletedDate + "</td>"
When I try this I get my JSON displayed.
html: "<td>" + goalcard.Name + "</td><td>" + goalcard.Customer + "</td><td>" + goalcard.PlannedDate + "</td><td>" + goalcard.CompletedDate + "</td><td>" + #Html.ActionLink("Ändra", "Edit") | #Html.ActionLink("x", "Inactive", new { #class = "deleteLink" }) + "</td>"
I also recieve a bunch of errors such as:
'return' statement outside of function'
Expected ';'
Syntax error
Expected identifier or string
Am I doing something wrong here?
This is the complete function:
result.forEach(function (goalcard) {
$("#GoalcardSearchResult tbody").append(
$('<tr/>', {
click: function() {
id = goalcard.Id;
var url = '#Url.Action("AnswerForm", "AnswerNKI", new { id = "__id__"})';
window.location.href = url.replace('__id__', id);
},
// steg Create a row for each result
html: "<td>" + goalcard.Name + "</td><td>" + goalcard.Customer + "</td><td>" + goalcard.PlannedDate + "</td><td>" + goalcard.CompletedDate + "</td><td>" + #(Html.ActionLink("Ändra", "Edit")) | #(Html.ActionLink("x", "Inactive", new { #class = "deleteLink" })) + "</td>"
}));
});
$('#GoalcardSearchResult tbody').trigger("update");
$("#GoalcardSearchResult").tablesorter();
});
return false;
Thanks in advance!
This code
"</td><td>" + #(Html.ActionLink("Ändra", "Edit")) | #(Html.ActionLink("x", "Inactive", new { #class = "deleteLink" })) + "</td>"
generates
"</td><td>" + Ändra | x + "</td>"
Note that generated anchors do not have string identifiers (' or "), so you get errors. You should change code to
"</td><td>" + '#(Html.ActionLink("Ändra", "Edit")) | #(Html.ActionLink("x", "Inactive", new { #class = "deleteLink" }))' + "</td>"

Categories