I've got an HTML table that's being returned using javascript return function. It works perfectly until I try to add an additional if clause into the middle of it.
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 is failing when I add the if clause. Is this a syntax issue? How do I go about breaking the HTML for a second so I can add additional javascript into the return? My goal in this is to add the td class red whenever the line's currency is in USD, but I can't figure out how to get this to work.
Using Ternary operator, eg:
... 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 ...
Your error is because, in essence, you're doing the equivalent of:
return "Something" + if(condition){}else{} + " else";
Which is illegal syntax for Javascript.
There are two solutions to this; the first is to use the inline if statement, as such:
return "Something" + (x == y ? "output if succeeded" : "output if not") + ".";
So your inline if would turn into:
+ (d.country !== "usd" ? '<td class="red">'+d.value+'</td>' : '<td class="black">'+d.value+'</td>') +
Or for a second solution, you could have an output string that you append things to, as 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With