Jquery "greater than" symbol - javascript

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.

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.

Access DOM element with a selector stocked in a variable

I am constructing a selector dynamically as following
...code before
my_selector = '"[data-my-selector=' + "'" + id + "'" + ']"';
alert( "The jQuery object is : " + $(my_selector) );
....
This code stops executing in the alert.
The selector is constructed properly and it's value is "[data-my-selector='453']" (if i alert(my_selector)). If i access $("[data-my-selector='453']") via the console, it works.
But when i try to access $(my_selector) from the console, i get the error
Error: Syntax error, unrecognized expression: "[data-my-selector='453']"
Do you have an idea what's the error ?
Thank you
The double quotes shouldn't be part of the variable. When you hardcode the string, you need the double quotes to denote that it's a string.
my_selector = '[data-my-selector="' + id + '"]';

Adding additional javascript inside javascript-generated HTML

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

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

Problem with type coercion and string concatenation in JavaScript in Greasemonkey script on Firefox

I'm creating a GreaseMonkey script to improve the user interface of the 10k tools Stack Overflow uses. I have encountered an unreproducible and frankly bizarre problem that has confounded me and the others in the JavaScript room on SO Chat. We have yet to find the cause after several lengthy debugging sessions.
The problematic script can be found here. Source - Install
The problem occurs at line 85, the line after the 'vodoo' comment:
return (t + ' (' + +(+f.offensive + +f.spam) + ')');
It might look a little weird, but the + in front of the two variables and the inner bracket is for type coercion, the inner middle + is for addition, and the other ones are for concatenation.
Nothing special, but observant reader might note that type coercion on the inner bracket is unnecessary, since both are already type coerced to numbers, and type coercing result is useless when they get concatenated into a string anyway. Not so! Removing the + breaks the script, causing f.offensive and f.spam to be concatenated instead of added together.
Adding further console.log only makes things more confusing:
console.log(f.offensive + f.spam); // 50
console.log('' + (+f.offensive + +f.spam)); // 5, but returning this yields 50 somehow
console.log('' + (+f.offensive + +f.spam) + ''); // 50
Source: https://chat.stackoverflow.com/transcript/message/203261#203261
The problem is that this is unreproducible - running scripts like
console.log('a' + (+'3' + +'1') + 'b');
in the Firebug console yields the correct result, as does
(function(){
return 'a' + (+'3' + +'1') + 'b';
})();
Even pulling out large chunks of the code and running them in the console does not reproduce this bug:
$('.post-menu a[id^=flag-post-]').each(function(){
var f = {offensive: '4', spam: '1'};
if(f){
$(this).text(function(i, t){
// Vodoo - please do not remove the '+' in front of the inner bracket
return (t + ' (' + +(+f.offensive + +f.spam) + ')');
});
}
});
Tim Stone in the chatroom has reproduction instruction for those who are below 10k.
This bug only appears in Firefox - Chrome does not appear to exhibit this problem, leading me to believe that this may be a problem with either Firefox's JavaScript engine, or the Greasemonkey add-on. Am I right?
I can be found in the JavaScript room if you want more detail and/or want to discuss this.
As part of the userscript's process, a <script> tag is injected into the page with the code retrieved by calling toString() on the function you've defined. Usually this would be fine, but it appears that there's a bug in the javascript engine used by Firefox 3.6.13 that relocates the parentheses in the expression, causing it to be evaluated in a very different way when the toString()-ified function is processed.
To illustrate this problem, we can run the following code in Firebug:
function f() { var a = '', b = '1', c = '2'; return a + '(' + (+b + +c) + ')'; };
f.toString();
This gives us this output:
function f() {
var a = "", b = "1", c = "2";
return a + ("(" + + b + + c + ")");
}
You'll note that the return expression has been modified. The parentheses have been relocated beyond the strings that were previously outside of them, causing the variables b and c to be coerced to strings and concatenated. This gives an unexpected result, since the expected addition never takes place. Unfortunately, this behaviour is present even when using Number() or parseInt() to coerce b and c.
There are several small modifications which change this, but the clearest is simply to save the result of the addition to a variable beforehand:
$(this).text(function(i, t){
var c = +f.offensive + +f.spam;
return (t + ' (' + c + ')');
});
Thankfully, this problem seems to not occur in the Firefox 4 beta, so hopefully this issue has been resolved going forward. Also, Matthew Flaschen has graciously gone ahead and filed a bug report (marked duplicate of 559438) so that the developers are made aware of this issue in either case.

Categories