jQuery append incorrectly displaying float number - javascript

its been an hour since i started working on this and i cand find the problem
this is my code inside the loop
$.each(data,function(key,game){
console.log(game.teams_odds[1].game_odds_value_modified);
var home_odds = parseFloat(game.teams_odds[0].game_odds_value_modified).toFixed(2);
var away_odds = parseFloat(game.teams_odds[1].game_odds_value_modified).toFixed(2);
console.log(away_odds);
$("#oddsTable").append('<tr>' +
'<td>' +
'<span class="red">Game ID : '+game.game_id+' </span>' +
'<br>'+game.game_start_time+'<br>' +
'</td>' +
'<td>' +
'<span class="teamName">'+game.teams_odds[0].team_name_eng+'</span>' +
'<span class="teamName">'+game.teams_odds[1].team_name_eng+'</span>' +
'</td>' +
'<td>' +
'<span style="display: block">' +
'<a href="{if $isDotNet == 0}/{$kioskUrl}/single-pop/{$dataHolders.team_home_game_details}/bettype/{$betType}/baseball/{else}/pop_bet.php?gdid={$dataHolders.team_home_game_details}{/if}" class="teamOdds{if $dataHolder.blink_it == 1 && $dataHolder.blink_it_game_details_id == $dataHolder.game_details_id_home} blinkMe{/if}" style="font-size: 15px; font-weight: bold;">' +
+home_odds+
'</a>' +
'</span>' +
'<span style="display: block">' +
'<a href="{if $isDotNet == 0}/{$kioskUrl}/single-pop/{$dataHolders.team_away_game_details}/bettype/{$betType}/baseball/{else}/pop_bet.php?gdid={$dataHolders.team_away_game_details}{/if}" class="teamOdds{if $dataHolder.blink_it == 1 && $dataHolder.blink_it_game_details_id == $dataHolder.game_details_id_away} blinkMe{/if}" style="font-size: 15px; font-weight: bold;">' +
+away_odds+
'</a>' +
'</span>' +
'<br>'+game.game_start_time+'<br>' +
'</td>' +
'</tr>'
);
});
when i try to use console.log() and alert() to show the values just fine, but when i see my rendered html from using append it the number lacks the number zero zero
say 1.60
becomes 1.6
console.log(away_odds) //1.60
alert(away_odds) //1.60
what i want is for it to display 1.60 but it keeps displaying 1.6

You've concatenated the previous line already:
'<a href="{if $isDotNet == 0} ... style="font-size: 15px; font-weight: bold;">' +
+away_odds+ // extra + --^
'</a>' +
Leading + on the second line is actually Unary Plus operator, which converts away_odds to a number again. Also home_odds will be converted to a number for the same reason.

toFixed(2) should only be used in the part of the code that outputs it.
In this case,
var home_odds = parseFloat(game.teams_odds[0].game_odds_value_modified);
var away_odds = parseFloat(game.teams_odds[1].game_odds_value_modified);
And where you are printing the variables use
home_odds.toFixed(2)
I have tested it and it works fine

Related

.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...

How to handle attribute with # in its name

I am facing to problem with Elasticsearch result which is using # in attribute name. Snippet of json result:
{"_index":"logs-2015.12.31","_type":"log","_id":"AVH4eA4QKV0mbJuiIHO1","_score":null,"_source":{"#timestamp":"2015-12-31T14:36:35.378Z","beat":{"hostname":"
I need to interpret its value into jquery code. See the code snippet:
case item._index.startsWith('logs-'):
$('#results-list').append( '<a href="details.jsp?id=' + item._id + '" target="_blank" class="list-group-item">'
+ '<span class="label label-info">' + item._type + '</span>'
+ '<h4 class="list-group-item-heading">' + item._source.source + '</h4>'
+ '<p class="list-group-item-text">' + item._source.#timestamp + ' - ' + item._source.beat.name + '</p>'
+ '<p class="list-group-item-text">' + item._source.message + '</p>'
+ '</a>'
How to handle the attribute if I cannot change the source?
The # character cannot be used in a literal property name, hence you need to use array notation to access it:
item._source['#timestamp']

Tablesorter with unknown # of columns

I am working with tablesorter and am building a header with the following code:
table.push(['<div class="first"></div>', '<div class="model">Model</div>',
'<div class="third" style="width: ' + ColumnWidth[3] + 'px;">' + ColumnNo[3] + '</div>',
'<div class="fourth" style="width: ' + ColumnWidth[4] + 'px;">' + ColumnNo[4] + ColumnUnit[4] + '</div>',
'<div class="fifth" style="width: ' + ColumnWidth[5] + 'px;">' + ColumnNo[5] + ColumnUnit[5] + '</div>',
'<div class="sixth" style="width: ' + ColumnWidth[6] + 'px;">' + ColumnNo[6] + ColumnUnit[6] + '</div>',
'<div class="seventh" style="width: ' + ColumnWidth[7] + 'px;">' + ColumnNo[7] + ColumnUnit[7] + '</div>',
'<div class="eighth" style="width: ' + ColumnWidth[8] + 'px;">' + ColumnNo[8] + ColumnUnit[8] + '</div>',
'<div class="ninth" style="width: ' + ColumnWidth[9] + 'px;">' + ColumnNo[9] + ColumnUnit[9] + '</div>',
'<div class="tenth" style="width: ' + ColumnWidth[10] + 'px;">' + ColumnNo[10] + ColumnUnit[10] + '</div>',
'<div class="eleventh" style="width: ' + ColumnWidth[11] + 'px;">' + ColumnNo[11] + ColumnUnit[11] + '</div>',
'<div class="twelfth" style="width: ' + ColumnWidth[12] + 'px;">' + ColumnNo[12] + ColumnUnit[12] + '</div>',
'<div class="thirteenth" style="width: ' + ColumnWidth[13] + 'px;">' + ColumnNo[13] + ColumnUnit[13] + '</div>',
'<div class="fourteenth "style="width: ' + ColumnWidth[14] + 'px;">' + ColumnNo[14] + ColumnUnit[14] + '</div>',
'<div class="fifteenth" style="width: ' + ColumnWidth[15] + 'px;">' + ColumnNo[15] + ColumnUnit[15] + '</div>',
'<div class="sixteenth" style="width: ' + ColumnWidth[16] + 'px;">' + ColumnNo[16] + ColumnUnit[16] + '</div>',
'<div class="seventeenth" style="width: ' + ColumnWidth[17] + 'px;">' + ColumnNo[17] + ColumnUnit[17] + '</div>']);
This works like a charm, however, I have no way of knowing how many columns will be needed ahead of time, so I need to build the array 'table' dynamically.
Here is what I have come up with for that:
var tableHeaderVar = [];
tableHeaderVar.push(['<div class="first"></div>']);
tableHeaderVar.push(['<div class="model">Model</div>']);
if (ColumnWidth[3] != 0) {
tableHeaderVar.push(['<div class="third" style="width: ' + ColumnWidth[3] + 'px;">' + ColumnNo[3] + '</div>']);
};
if (ColumnWidth[4] != 0) {
tableHeaderVar.push(['<div class="fourth" style="width: ' + ColumnWidth[4] + 'px;">' + ColumnNo[4] + ColumnUnit[4] + '</div>']);
};
.
.
.
table.push([tableHeaderVar]);
Basically, this checks the set width, which will be 0 if no column is selected. Then, checks the widths for each column to decide whether the column gets included in the array. This code will build the header vertically down the left side of the table, rather than across the top. I captured the output for both methods and used Beyond Compare to compare them. They are compared as "Binary Same", which should mean they are absolutely identical.
First I tried using individual table.push statements, but the results were about the same. I thought maybe the header (and table data) needed to be pushed as a group, so I decided to use one array variable (tableHeaderVar) to build the HTML and then push it all to table at once. Unfortunately, something seems to be not quite right with my method.
Would anyone happen to know something that might work?
Edit
There appears to be no resulting HTML for the datatable in either the working (static # of columns) or non-working (# of columns set on the fly) versions. Here is the HTML placeholder for the table (it is identical in both):
<div id="data-grid" class="datagrid">
<div id="testtable"></div>
</div>
As you can see, it's empty. Here is my tablesorter declaration:
$('#testtable').tablesorter({
theme: 'default',
widthFixed: false,
widgets: ['stickyHeaders'],
widgetOptions: {
build_source: table,
build_headers: {
rows: 1,
classes: [],
text: []
},
build_footers: {
rows: 0
}
}
});
Sure, but it might not be the answer you are looking for.
There are already tools out there for sorting tables so if you get sick of making your own.
Here is one for example.
I believe I have found the answer. The main issue was that when using the tablesorter build table widget, passing an array (in this case used to add the required columns one at a time) into another array (used as the datasource for the build table widget) simply won't work correctly. After comparing the results of the two arrays, I didn't find any differences, but there was something there that was throwing it off. Also, the datasource array cannot be built one value at a time. At least, I didn't have any luck with that.
Here is what I had to do:
var tableHeaderVar = [];
tableHeaderVar.push(['<th><div class="first"></div></th>']);
tableHeaderVar.push(['<th><div class="model">Model</div></th>']);
if (ColumnNo[3] != null) {
tableHeaderVar.push(['<th><div class="third" style="width: ' + ColumnWidth[3] + 'px;">' + ColumnNo[3] + '</div></th>']);
};
if (ColumnNo[4] != null) {
tableHeaderVar.push(['<th><div class="fourth" style="width: ' + ColumnWidth[4] + 'px;">' + ColumnNo[4] + ColumnUnit[4] + '</div></th>']);
};
.
.
.
table = '<thead>' + tableHeaderVar + '</thead>';
So, as you can see, I built an array dynamically to include each column that was needed using the <th> tag. Then, after all the columns were selected, I passed that array into a string variable and enclosed it with the thead tag.
I did something very similar with the table body, except used the <td> tag. As I looped through each datarow, I enclosed each with the <tr> tag. These tags didn't appear to be needed when using an array as the datasource, but when using a string value, they were crucial.

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

Missing before statement

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.

Categories

Resources