Adding additional javascript inside javascript-generated HTML - javascript

This seems like a simple question, but I don't know the correct syntax to make it work.
I have this code that's used by DataTables to generate a table:
'<td>'+d.expirationDate+'</td>'+
'<td>'+d.dateReceived+'</td>'+
I'd like to add a qualifier onto this that if the date field is not set, to display nothing instead of the word null.
So I tried this:
'<td class="dropInfo">'+
if (d.debitExpDate !== 'null') {
d.expirationDate
}
+'</td>'+
but I get an error. Uncaught SyntaxError: Unexpected token if
What's the correct syntax for this?

use a logical or ||
'<td>'+d.expirationDate+'</td>'+
'<td>' + (d.dateReceived || '') + '</td>'
|| evalutes the first thing on the left. If the left is "truthy" then it uses that value otherwise it uses the second thing.
Since null is not a truthy value in this case it will choose the empty string.

Several solutions are available.
Solution1: One line synthaxe, as pointed out by #Tom DDD (see his post)
'<td>'+d.expirationDate+'</td>'+
'<td>' + (d.dateReceived || '') + '</td>'+
Solution2 : Split the generation of your js with ; and concacenate with +=
var js = '<td class="dropInfo">';
if (d.debitExpDate !== 'null') {
js +=d.expirationDate
}
js+='</td>'

The other answers are just fine, but there is another common option:
'<td>'+(d.expirationDate===null ? '' : d.expirationDate)+'</td>'
The advantage here is that more complex conditions can also be used. for example:
'<td>'+(d.expirationDate>Date.now() ? '' : d.expirationDate)+'</td>'

Related

Use Go to read a file for use in javascript rendering

I have seen many articles about Go Arrays being used with Javascript but I am trying to do something a little different. I want to read a configuration file using Go, since it has access to the server side, and use it in a javascript function that will be rendered with the template. This is to avoid hard coding values in the JavaScript:
I want to change this:
javaString += "function isValidPrefix() {"
javaString += "forbidden_prefixes = [ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\" ];"
... more javascript ...
javaString += "}"
to something that puts the prefixes in a file, so that I don't have to recompile every time I want to add a prefix.
So I tried this:
var configArr []string
configArr = LoadFile("/conf.dat")
javaString += "forbidden_prefixes = [];"
for _, eachline := range configArr {
javaString += "forbidden_prefixes.push(\" + eachline + \");"
fmt.Println(eachline)
}
eachLine prints out correctly in the for loop but forbidden_prefixes contains one element + eachLine + which I am assuming is a syntax error but even if I try to retrieve the DOM element's value to check it against, the web console says the element doesn't exist. Everything worked fine with the hardcoded values. Am I doing something wrong or is it simply just not possible?
You are building a string using literals, without using the variable you intended to use. Try this:
javaString += fmt.Sprintf("forbidden_prefixes.push(\"%s\");",eachline)
The issue indeed comes from your syntax. You escaped the quotes so the + operators are actually part of the string. Here are two possible solutions:
javaString += "forbidden_prefixes.push(\"" + eachline + "\");"
Or
javaString += fmt.Sprintf("forbidden_prefixes.push(%q);", eachline)
%q adds quotes around the value it's replaced with.

JavaScript Undefined issue from a JSON string

I am trying to add data from a JSON string to a table in the following way:
tr = "<tr><td>" + data[i]["code"] + "</td><td>" + data[i]["codeDesc"] + "</td></tr>";
But on execution I get:
undefined<tr><td>C1713</td><td>ANCHOR/SCREW OPPOSING BN-TO-BN/SOFT TISSUE-TO-BN</td>
I don't understand why this 'undefined' is getting appended.
what you use jquery or pure javascript ?
if you use jquery you should write something like
$("yourId").html(tr);
if you use pure javascript must be
document.getElementById("yourId").innerHtml = tr;
if you don't specificate this call undefined because the javascript don't know if this is only text or html tag .

Create javascript string with conditional and non conditional variables

I'm creating a single string using some defined variables like so:
var name = 'John';
var business = 'Google';
var email = name + ' registered the business ' + business;
In reality this is from a form submission so the variables will be set in a form and sent to my NodeJS backend to create this string. The user may or may not enter a message. I've created an if statement to add it to the string if they have:
if (message) email += '<br /><br />Message: ' + message;
The problem is when I expand this logic, it can get very messy. For example if I want to add several conditional variables to various points in the middle of the original string. Is there a way to do the conditional logic inside the initial string build?
Use a ternary operator. It can still get messy, but it reduces "if" everywhere.
var email = name + ' registered ' + business
+ (message ? '<br /><br />Message: ' : '') // conditional line
+ more_stuff...;
There are many ways you could structure the code to clean things up. A simple solution would be creating an object that keeps track of your various inputs, and then you could loop through that object to append all necessary items.
For example:
var obj = {
message: messageField,
messageTwo: messageTwoField
}
for (keys in obj){
if (key == message && obj.key) {
//append the string to a specific place
}
}
There are many ways to potentially solve this, but by storing everything in one object that can help to clean things up. Also, the if statement is conditional based on the key name and if there is a value assigned to that key name. This of course is just my opinion on how you could approach this, the size and complexity of the app could greatly change this answer.

executing javascript inside href attribute of anchor tag

I checked a lot on Hrefs but couldn't get something related.
I am trying to do this in code behind which is actually a custom control class
writer.Write("<a href='javascript:document.location.href?" + filter.ParameterName + "=" + filter.QueryValue + "'>" + filter.UserVisibleValue + "</a>| ");
now this gets me something like this on hover of above anchor 'document.location.href?Test one=2013' and when i click it, this throws an obvious javascript error 'SyntaxError: missing : in conditional expression' because it takes it as a conditional operator and hence finds : missing.
I simply want that document.location.href (current url) should be calculated and the value put in where i use it.
I know that i may simply call a javascript function and inside that function i set the href but can i do it this way?
Try this:
writer.Write("<a href='javascript:window.location = document.location.href?" + filter.ParameterName + "=" + filter.QueryValue + "'>" + filter.UserVisibleValue + "</a>| ");
Note that you might have to escape values as needed otherwise JavaScript will become invalid. To prove that above approach works, you can copy-paste following simpler example in any HTML page and see it working:
bla

Jquery "greater than" symbol

When I use below notation with '>' in line
$('#tablesorter > tbody')
in code
var message;
myService.getUsers({ callback : function(str) {
message= jQuery.parseJSON(str);
}});
$.each(message, function() {
$('#tablesorter > tbody').append(
'<tr><td>' + this.name
+ '</td><td>' + this.surname
+ '</td>' + '</tr>');
});
Note: myservice is a dwr service, don't know if it is related
I have error in chrome console
Uncaught Error: Syntax error, unrecognized expression: >
> means >
When I deleted the > the error disappears but it does not work as expected
the greater than > symbol is used in CSS selectors (which jQuery selectors are based on) to indicate a "direct descendent".
Documentation
The code you posted works fine, the > symbols in there would not cause any errors.
Wherever you're outputting your code, it's getting transformed to automatically escape. Perhaps you have a templating language in between.
You need to either store all of your javascript code in a separate file (the best solution), or find a way with your pages (JSP?) to disable output escaping.

Categories