Embed javascript in javascript html return
I have an HTML table returned using a javascript function return
. It works great until I try to add an additional sentence if
in the middle.
function format ( d ) {
return '<div class="slider">'+
'<table id="expand">'+
'<tr>'+
'<td><button class="btn btn-success" value="Save" onclick="saveItem(this)" data-soli="'+d.soli+'" data-comments="'+d.comments+'" >Save</button></td>'+
'</tr>'+
'<tr>'+
'<td class="dropHeader">Customer</td>'+
'<td class="black">'+d.customer+'</td>'+
'<td class="dropHeader">Value</td>'+
if (d.country !== "usd") {
'<td class="red">'+d.value+'</td>'+
} else {
'<td class="black">'+d.value+'</td>'+
}
'<td class="dropHeader">Comments</td>'+
'<td class="black"><input onblur="submitComments(this.value)" type="text"><br>'+d.comments+'</input></td>'+
'</tr>'+
'</table>'+
'</div>';
}
The code doesn't work when I add a suggestion if
. Is this a syntax problem? How do I start parsing HTML for a second to add extra javascript to return? My goal is to add a td class red
whenever the line currency is in USD, but I cannot figure out how to get this to work.
source to share
Do it like this
function format ( d ) {
var cssClass="";
if (d.country !== "usd") {
cssClass="red";
}
else{
cssClass="black";
}
return '<div class="slider">'+
'<table id="expand">'+
'<tr>'+
'<td><button class="btn btn-success" value="Save" onclick="saveItem(this)" data-soli="'+d.soli+'" data-comments="'+d.comments+'" >Save</button></td>'+
'</tr>'+
'<tr>'+
'<td class="dropHeader">Customer</td>'+
'<td class="black">'+d.customer+'</td>'+
'<td class="dropHeader">Value</td>'+
'<td class="'+cssClass+'">'+d.value+'</td>'+
'<td class="dropHeader">Comments</td>'+
'<td class="black"><input onblur="submitComments(this.value)" type="text"><br>'+d.comments+'</input></td>'+
'</tr>'+
'</table>'+
'</div>';
}
source to share
Using Ternary Operator like:
... etc ...
+
'<td class="dropHeader">Value</td>'
+
(d.country !== "usd" ? '<td class="red">'+d.value+'</td>' : '<td class="black">'+d.value+'</td>')
+
'<td class="dropHeader">Comments</td>'
+
... etc ...
source to share
Your mistake is that, in essence, you are doing the equivalent:
return "Something" + if(condition){}else{} + " else";
This is illegal syntax for Javascript.
There are two solutions, firstly, use the inline if statement as such:
return "Something" + (x == y ? "output if succeeded" : "output if not") + ".";
So your inline if it turned into:
+ (d.country !== "usd" ? '<td class="red">'+d.value+'</td>' : '<td class="black">'+d.value+'</td>') +
Or for the second solution, you might have an output line to which you add things, like so:
function format(d){
var output = "";
output += "Testing code";
if(d.country !== "usd"){
output += "Woo we succeeded";
}
output += " more testing <i>code<i>.";
return output;
}
source to share