Function replicating items - javascript

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

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 === "").

How to assign a unique number to every object returned in a jQuery each loop?

I'm using AJAX to call a Flickr JSON file that brings in all of my photo data. The data then runs through an each loop where variables are collected which are then used to concatenate a string for each photo and write them into a custom lightbox.
For the lightbox, I am using this W3 lightbox tutorial as the container for the photos.
My question is how do I create a number variable and assign it to the objects in my each loop so that I can create something like this:
onclick="openModal();currentSlide(foo)"
For example, if there are 5 objects in my each loop, I want each to be assigned a variable starting with 1 and increasing to 5.
//Call all images from Flickr
var photoSettings = {
"async": true,
"crossDomain": true,
"url": "https://api.flickr.com/services/rest/?method=flickr.photos.search&...&format=json&nojsoncallback=1",
"method": "GET",
"headers": {}
}
$.ajax(photoSettings).done(function (data2) {
$.each( data2.photos.photo, function( i, gp ) {
var farmId2 = gp.farm;
var serverId2 = gp.server;
var id2 = gp.id;
var secret2 = gp.secret;
var title2 = gp.title;
var description2 = gp.description._content;
$('.flickrContain').on('click', function() {
if ($(this).attr('alt') == '2017—Yonge St., Richmond Hill'){
if ((title2.indexOf( 'Y2' )> -1) && (title2.indexOf( '2017' )> -1)){
var foo = assign a number to each of the conditional objects
//main image slider
$('.image-slider').append('<div class="mySlides"><img src="https://farm' + farmId2 + '.staticflickr.com/' + serverId2 + '/' + id2 + '_' + secret2 + '.jpg" width="100%" alt="' + description2 + '" title="' + description2 + '" id="H2BandC-2017-' + id2 + '"/></div>');
//thumnails
$('.image-list').append('<li class="flickrSliderImg"><img class="demo" src="https://farm' + farmId2 + '.staticflickr.com/' + serverId2 + '/' + id2 + '_' + secret2 + '.jpg" alt="' + description2 + '" title="' + description2 + '" width="160px" height="90px" border="0" onclick="currentSlide(' + foo + ')"/></li>');
};
} else if ($(this).attr('alt') == '2016—Yonge St., Richmond Hill'){
if ((title2.indexOf( 'Y2' )> -1) && (title2.indexOf( '2016' )> -1)){
var foo = assign a number to each of the conditional objects
//main image slider
$('.image-slider').append('<div class="mySlides"><img src="https://farm' + farmId2 + '.staticflickr.com/' + serverId2 + '/' + id2 + '_' + secret2 + '.jpg" width="100%" alt="' + description2 + '" title="' + description2 + '" id="H2BandC-2016-' + id2 + '"/></div>');
//thumnails
$('.image-list').append('<li class="flickrSliderImg"><img class="demo" src="https://farm' + farmId2 + '.staticflickr.com/' + serverId2 + '/' + id2 + '_' + secret2 + '.jpg" alt="' + description2 + '" title="' + description2 + '" width="160px" height="90px" border="0" onclick="currentSlide(' + foo + ')"/></li>');
}
}
});
});
});
From the docs you can see that when you call each, you can define an index parameter for the function you pass to it:
jQuery.each( arr, function( index, val ) {
$( "#" + val ).text( "Mine is " + val + "." );
// Will stop running after "three"
return ( val !== "three" );
});
Thanks #LajosArpad! You sent me in the right direction. The following code worked to place the index value of the thumbnail in currentSlide();
$('img.demo').each(function (index){
$(this).attr('onclick', 'currentSlide(' + index + ')');
});
I also rewrote the .append code above to:
.append('...onclick=""...')

how to start each function from index 1 to post json objects in different div in html

I have this json data
somehow i displayed this part of data in html
and want to display this part of data
into div in html but i am unable to display it using for loop and don't to how to start each function from index 1 as index 0 in personal details data.
here is my code
var url = "http://localhost/ReadExchange/api.php";
$.getJSON(url, function(data) {
if (data) {
alert("hey got the data" + JSON.stringify(data));
var arr = data.length;
//$.each(data, function(i,element) {
var element = data[0];
$("#postjson").append(
'<div id="' + element.id + '">' + '<p>' + 'FirstName:' + element.FirstName + '<br/>'
+ 'MiddleName:' + element.MiddleName + '<br/>' + 'LastName:' + element.LastName + '<br/>' + 'Gender:' + element.Gender + '<br/>' + 'Location:' + element.Location + '<br/>' + 'Email:' + element.Email + '<br/>' + 'Mobile:' + element.Mobile + '<br/>' + '</p>' + '</div>'
);
for (var i = 1; i < arr; i++) {
$("#postjson").append(
'<div id="">' + '<p>' + 'BookTitle:' + data[i].data.BookTitle + '<br/>' + 'BookGenre:' + data[i].data.BookGenre + '<br/>' + 'BookWriter:' + data[i].data.BookWriter + '<br/>' + 'Gender:' + data[i].data.BookDescription + '<br/>'
+ '</p>' + '</div>'
);
}
} else {
return;
}
You can use Array.prototype.splice()
data.splice(0, 1);
then iterate data array at for loop, with i set to 0
var data = [{abc:123}, {def:456}];
data.splice(0, 1);
for (var i = 0; i < data.length; i++) {
alert(JSON.stringify(data))
}

Expected an assignment or function call and instead saw an expression?

I keep getting this error:
"Expected an assignment or function call and instead saw an expression and instead saw an expression”
when trying to use Javascript to append my table.
Can anyone help me rectify this?
$('#lbUsers tbody').append('<tr><td>' + row.Number + '</td><td> ' + row.Name + '</td><td> ' + row.points + '</td><td>`' + row.stars + ' </td><td>' + row.Type '</td></tr>');
Full code:
$('#lbUsers').html('');
db.transaction(function (transaction) {
transaction.executeSql('SELECT * FROM People;', [],
function (transaction, result) {
if (result !== null && result.rows !== null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
`$('#lbUsers tbody').append('<tr><td>' + row.Number + '</td><td> ' + row.Name + '</td><td> ' + row.points + '</td><td>`' + row.stars + ' </td><td>' + row.Type '</td></tr>');
}
}
}, errorHandler);
}, errorHandler, nullHandler);
return;
}
HTML:
<table id="lbUsers">
<tbody>
<th>Number</th><th>Name</th><th>Points</th><th>Stars</th><th>Type</th>
</tbody>
</table>
The problem is with the following line:
`$('#lbUsers tbody').append('<tr><td>' + row.Number + '</td><td> ' + row.Name + '</td><td> ' + row.points + '</td><td>`' + row.stars + ' </td><td>' + row.Type '</td></tr>');
There should not be a leading ` character. Also, you are missing a concatenation operator ("+") after row.Type.

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

Categories