Missing before statement - javascript

I have the following piece of code that I would like to style:
var dateString = val.date; // this display my blog post date e.g. "2013-09-02 15:04:50"
var split = dateString.split(' ');
output += '<div class="postxt">' (split[0] +" at "+ split[1]) '</div>';
How can I add a span or a div for both split0 & split1
Thanks

Just add the SPAN to the HTML, the same way you do the DIV.
output += '<div class="postxt"><span class="date">' + split[0] +
'</span> at <span class="time">' + split[1] + '</span></div>';
You also need to use + to concatenate the HTML elements with the variables.

Your braces should be pluses in the last line:
output += '<div class="postxt">' + split[0] + " at " + split[1] + '</div>';
Note that you can leave the braces in, but they are neither required nor do they make any differences when concatenating strings:
output += '<div class="postxt">' + (split[0] + " at " + split[1]) + '</div>';
Add whatever divs, spans, style classes you want:
output += '<div class="postxt"><span class="foo">' + split[0] + "</span> at <span class="bar">" + split[1] + '</span></div>';
The error "Missing ... before statement" you got was only on the JavaScript level, it has nothing to do with adding further HTML elements.

Related

Trouble with jQuery loop through array of objects

I'm trying to nest 3 divs within a "row" div.
I had this working in "long format" (multiple var's instead of looping through the array). I've refactored my code and now I don't get any error codes AND my code does not append to the HTML file. When I console log I get an array with 3 objects. I'm sure i'm missing something minor.
Anyways some help would be great!
<div class="row">
**nested divs go here.
</div>
$(document).ready(function() {
$.get("http://api.openweathermap.org/data/2.5/forecast/daily?id4726206&cnt=3", {
APPID: "MY API KEY",
lat: 29.423017,
lon: -98.48527,
units: "imperial"
}).done(function(data) {
var stationId = data.city.name;
// Stattion Name
$('#station').append(stationId);
//console.log(data);
var forecast = data.list;
//Wind Direction in Compass Format
function getDirection(dir) {
var compass = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
var result = Math.floor((360 - dir) / 22.5);
return compass[result];
}
//Forecast Variables
$.each(forecast, function(i, v) {
var html = '';
html += "<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>";
html += "<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°';
html += " / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>";
html += "<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon;
html += ".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main;
html += "</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>";
html += "<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>";
html += "<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed));
html += " mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>";
html += "<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div>";
return html;
});
$('.forecast').append(forecast);
console.log(forecast);
});
});
You are trying to append the array forecast in html. which wont work. You should declare the html variable outside and then use it in append function.
I will also recommend to use string builder logic using array and then convert it to string and append it. remember string concatenation is heavy operator as it creates new instance of elememt every time concatenation is done :
var html = [];
$.each(forecast, function(i, v) {
html.push("<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>");
html.push("<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°');
html.push(" / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>");
html.push("<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon);
html.push(".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main);
html.push("</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>");
html.push("<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>");
html.push("<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed)));
html.push(" mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>");
html.push("<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div></div>");
});
$('.forecast').append(html.join(""));

Why are there additional quotes on the ID of HTML <p> tags which are set in JavaScript using .innerHTML.?

I am trying to set the content of a div which has the id "results" to have the value of a variable (i). I also want to set the ID of the element to the value of another variable (a).
var i="somecontent";
var a=0;
document.getElementById("results").innerHTML += "<p "
+ "id=" + """ + a + "" " + "\>" + i + "<p/>
This however, is resulting in the ID of the <P> tag being id=""0"" rather than id="0".
Here is the output:
<p id=""0"">somecontent</p>
However, I want to display:
<p id="0">somecontent</p>
What can I do to remove the extra quotations?
Those extra quotation marks are the " character references you put in. Character references are HTML and therefore parsed by the HTML parser, not the JavaScript parser. Since " is a way of representing a literal double quote character without having it be treated specially by the HTML parser, the parser thinks you intended for it to be part of the attribute value, and that's what you get.
If you were intending to add escaped quotes to your HTML that don't interfere with the JavaScript parser, escape them with backslashes or use single quotes instead:
document.getElementById("results").innerHTML += "<p id=\"" + a + "\">" + i + "</p>";
document.getElementById("results").innerHTML += "<p id='" + a + "'>" + i + "</p>";
You can also leave them out entirely, unless you're writing XHTML for some reason:
document.getElementById("results").innerHTML += "<p id=" + a + ">" + i + "</p>";
Try this:
document.getElementById("myDiv").innerHTML += "<p "
+ "id=" + a + "\>" + i + "<p/>";
A better way: "id=\"" + a + "\"" + "\>" + i + "
You only need to use the html codes like " in your html.
Javascript handles " just fine.
Removed html codes:
var i="somecontent";
var a=0;
document.getElementById("results").innerHTML += "<p " + "id=\'" + a + "\'/>" + i + "</p>"
Use createElement, createTextNode and appendChild
I do not recommend numeric IDs - they will come back and bite you.
This is a preferred method - I assume you have a loop
window.onload=function() {
var par,text,res = document.getElementById("results");
var content = ["Paragraph1","Paragraph2","Paragraph3"];
for (var i=0;i<content.length;i++) {
par = document.createElement("p");
par.id = "A"+i;
text = document.createTextNode(content[i]);
par.appendChild(text);
res.appendChild(par);
}
}
<div id="results"></div>
Your inner HTML quotes are misplaced. Try this:
var i = "somecontent";
var a="0";
var j = document.getElementById("results").innerHTML += '<p id="' + a + '">' + i + '</p>';
console.log(i);
console.log(j);
<Div id="results"></Div>

.html() jQuery function return NaN

I have
<div id="tablePlace"></div>
And
if ($('#radioOne').is(':checked') == true) {
$("#tablePlace").html(" ");
$("#tablePlace").append(htmlTable); //htmlTable is a string that contains an html table code
loadNestedTable(temp);
}
It works but in the div I find NaN.
If I comment $("#tablePlace").append(htmlTable);, NaN doesn't appear.
Why?
UPDATE
htmlValue code:
var tab = '<table id="decretoSingolo">'+
+'<thead>'
+ '<tr>'
+ '<th>Ente</th>'
+ '<th>CUP</th>'
+ '<th>Decreto impegno</th>'
+ '<th>Data decreto impegno</th>'
+ '<th>Importo impegno</th>'
+ '<th>Finanziato MIUR</th>'
+ '<th>Importo pagato</th>'
+ '<th>Importo in pagamento</th>'
+ '</tr>'
+ '</thead>'
+ '<tbody>'
+ '</tbody>'
+'</table>'
+'<div style="display:none">'
+ '<table id="dettagliDecretoSingolo">'
+ '<thead>'
+ '<tr>'
+ '<th>Progressivo pagamento</th>'
+ '<th>Data decreto</th>'
+ '<th>Numero decreto pagamento</th>'
+ '<th>Tipo pagamento</th>'
+ '<th>Importo in pagamento</th>'
+ '<th>Nota decreto</th>'
+ '</tr>'
+ '</thead>'
+ '<tbody>'
+ '</tbody>'
+ '</table>'
+'</div>';
htmlTable value:
<table id="myTable">NaN<tr><th>Ente</th><th>CUP</th><th>Decreto impegno</th><th>Data decreto impegno</th><th>Importo impegno</th><th>Finanziato</th><th>Importo pagato</th><th>Importo in pagamento</th></tr></thead><tbody></tbody></table><div style="display:none"><table id="myTableDetails"><thead><tr><th>Progressivo pagamento</th><th>Data decreto</th><th>Numero decreto pagamento</th><th>Tipo pagamento</th><th>Importo</th><th>Nota</th></tr></thead><tbody></tbody></table></div>
NaN appears after .append(). There is a problem in the htmlTable code?
The problem is that you have a unary + in your code:
var tab = '<table id="decretoSingolo">'+
+'<thead>'
// ^--- Here
To fix it:
Remove one of the +s. Usually it's best to use the + at the end of the previous line, to avoid issues with automatic semicolon insertion.
Why you're getting NaN:
It's a unary + because it follows the + at the end of the previous line, with whitespace in-between them (so it's not ++ as I initially suggested).
That unary + will try to take its operand (the string that follows it) and convert it to a number, and if that can't be done will yield NaN. Then the operands to the + on the previous line are a string and a number, so that addition operator converts the string to number and adds it to NaN (which yields NaN).
You can see it here:
var tab = '<table id="decretoSingolo">'+
+'<thead>'
+ '<tr>';
document.body.innerHTML = tab;
Side note: There's no need to do .html(" ") and then .append(htmlTable), just do .html(htmlTable).
You have double plus sign + in the following lines, remove one :
var tabellaDecretoSingolo = '<table id="decretoSingolo">'+
+'<thead>'
+ '<tr>'
Should be :
var tabellaDecretoSingolo = '<table id="decretoSingolo">'
+'<thead>'
+ '<tr>'
Hope this helps.
First, you can optimise your javascript:
if ($('#radioOne').is(':checked') == true) {
$("#tablePlace").html(" ");
$("#tablePlace").append(htmlTable); //htmlTable is a string that contains an html table code
loadNestedTable(temp);
}
by
if ($('#radioOne').is(':checked') == true) {
$("#tablePlace").html(htmlTable); //html() replace all content of your element child.
loadNestedTable(temp);
}
Also, you've a problem when you define your "htmlTable" value
<table id="myTable">NaN<tr> [...]
check after your ">" of your element if you don't add a NAN var...

Blogger data tags don't work in javascript

Hy, I have some issues when adding blogger data tags to javascript.
var summary1 = '<div class="firstWrap">' + '<h3 class="post-title entry-title">' + '</h3>' + '<div>' + removeHtmlTag(div.innerHTML,summ) + '</div>' + '<span class="readmorebutton">' + '<a expr:href="data:post.url">' + 'Read More »' + '</a>' + '</span>' + '</div>' + imgtag;
div.innerHTML = summary1;
}
The code adds the div first wrap the read more button and the summaries but it won't load the h3 and the a expr:href= data doesn't work.
How can I add the blogger data expr:href=... and other blogger code into javascript so that it works.
Thanks
You must define the expr:href="data:post.url" via Javascript variable in separated script tag. Simply like this:
<script type="text/javascript">
var postlink="<data:post.url/>"
</script>
You can place that script before or after your entry-container.
Then, call the variable in your script:
var summary1 = '<div class="firstWrap">' + '<h3 class="post-title entry-title">' + '</h3>' + '<div>' + removeHtmlTag(div.innerHTML,summ) + '</div>' + '<span class="readmorebutton">' + '' + 'Read More »' + '' + '</span>' + '</div>' + imgtag;
div.innerHTML = summary1;
}
I use this method in my blogger template, and it's works good for me.

Jquery / Javascript: There is a NaN on my HTML

I am writing an HTML loop using javascript. It will loop through a series of images and display them with additional information. It appears that there is always a NaN showing on the HTML output as shown here.
Here is the javascript in question:
var caption = '<p></p>';
if($.isEmptyObject(data[i].caption) !== true)
{
caption = '<p class="caption" style="top:'+data[i].height+'px;">'+
data[i].caption +
'</p>';
}
var li = '<li data-uk-modal="{target:#modal-open-image}"'
+ 'class="open"'
+ 'image="'+ data[i].photo +'"'
+ 'caption_height="'+ data[i].height +'"'
+ 'caption="'+ data[i].caption +'">'
+ '<a href="#" class="uk-thumbnail uk-overlay-toggle">'
+ '<div class="uk-overlay">'
+ '<img src="'+ data[i].photo +'" width="250px"/>'
+ caption +
+ '<div class="uk-overlay-caption">'
+ '<p> Sender: ' + data[i].sender + '</p>'
+ '<p> Date: ' + data[i].date + '</p>'
+ '<p> limit: '+ data[i].limit + '</p>'
+ '<p> counter: ' + data[i].counter + '</p>'
+ '</div>'
+ '</div>'
+ '</a>'
+'</li>';
$photo.append(li);
I would think the problem would lie on the caption variable. the data[i] is an array of from a database query.
I need to check if there is something on the data[i].caption. I tried using length, but that doesn't work, so I check if the object exist. Though I am not sure if that works.
My question, is how to display properly check if the caption is empty, and if none it will not add anything on the var li.
Thanks.
You can code it in one line:
( (data && data[i] && data[i].caption) ? " your stuff " : "")
But pay attention that checking 'data[i].caption' in javascript means that: zero is false, empty string is false.
Furthermore if you referring a number you can add a condition using the method isNaN
Please use this one in place of the '+ caption +'
isNaN(data[i].caption) ? '' : data[i].caption
or if(isNaN(data[i].caption)==true){
//do somthing
}else{
//do somthing
}
Thanks for the feedback. I manage to gobble up the solutions you game me and I ended up with this.
var height = (data[i].height == null)?0:data[i].height;
var caption= (data[i].caption== null)?'':data[i].caption;
var li = '<li data-uk-modal="{target:\'#modal-open-image\'}"'
+ 'class="open"'
+ 'image="'+ data[i].photo +'"'
+ 'caption_height="'+ height +'"'
+ 'caption="'+ caption +'">'
+ '<a href="#" class="uk-thumbnail uk-overlay-toggle">'
+ '<div class="uk-overlay">'
+ '<img src="'+ data[i].photo +'" width="250px"/>'
+ '<p class="caption" style="top:' + height +'px;">'
+ caption
+ '</p>'
+ '<div class="uk-thumbnail-caption">'
+ '<p> Sender: ' + data[i].sender + '</p>'
+ '<p> Reciever: '+ data[i].reciever + '</p>'
+ '<p> Date: ' + data[i].date + '</p>'
+ '<p> limit: '+ data[i].limit + '</p>'
+ '</div>'
+ '</div>'
+ '</a>'
+'</li>';

Categories

Resources