javascript expression expected - javascript

I am still new a Javascript tried earching and tried the development tool in Chrome, too see if I could find the problem.
Working in Intellij IDEA 13, Java, javascript and xhtml.
My problem is that I have a piece of javascript, then in IDEA when moused over, says that
Expression Expected
the javascript code looks the following
<script type="text/javascript>
function nameOfFunction(){
if(#{trendAnalysisLocationReportController.model.showTargetLine}){
this.cfg.series[this.cfg.data.length-1].pointLabels = {
show: false
};
}
}
<\script>
the method in the if sentence is a java method with a boolean return value.
the error is shown when hovering
'#{'
if Had a look at the following questions, before :
Expected Expression
boolean in an if statement
But didnt get me a solution.
what Iam I doing wrong ?

It looks as though the problem is the part that you've got within the #{...} block. Without knowing the context, it's hard to be sure, but is this something in a view/JSP page that's supposed to be replaced with a property at runtime? The if block will expect the part inside the brackets to be a boolean value, so if that's rendered to either 'true' or 'false' it would execute at runtime but would likely show the error you're seeing in your IDE as it's not actually a valid piece of JavaScript. If, on the other hand, you're expecting to be able to call your Java method/property from your JavaScript code, you're going to need to do something that requests that value from the server-side code - AJAX or similar.
Also worth noting that we can't see what this.cfg is supposed to represent. If that's your entire script block, then there's nothing that defines the cfg object within the current scope.
One last thing, you should change the <\script> end element to as it won't be understood properly by some browsers.

Related

Please explain this usage of a colon in javascript

I'm making a library, and I often inspect the result of Closure Compiler's output to see how it's doing things (I do have unit tests, but I still like to see the compiled code for hints of how it could compress better).
So, I found this very weird piece of code, which I never seen before.
variable : {
some();
code()
}
Note: this is not an object literal! Also, there is no ? anywhere that would make it a ?: conditional.
That code is in a regular function block (an IIFE).
variable, in this case, is an undefined variable. There's no code making it true, false, or whatever, and just to make sure, I put a console.log in there and indeed, I get a ReferenceError.
Please do note that I test my code in IE8 too, so this isn't just in modern browsers. It seems to be standard, plain old javascript.
So let's experiment with it. Firing up Chrome's console, I get this:
undeclaredVariable:{console.log('does this get logged?')} // yes it does.
trueValue:{console.log('what about this?')} // same thing.
falseValue:{console.log('and this?')} // same thing.
but then...
(true):{console.log('does this work too?')} // SyntaxError: Unexpected token :
...and...
so?{console.log('is this a conditional?')}:{alert(123)} // Unexpected token .
So what does it do?
thisThing:{console.log('is used to declare a variable?')}
thisThing // ReferenceError: thisThing is not defined
Please, I'd love it if someone could explain to me what this code is meant to do, or at least what it does.
It is a label
Provides a statement with an identifier that you can refer to using a
break or continue statement.
For example, you can use a label to identify a loop, and then use the
break or continue statements to indicate whether a program should
interrupt the loop or continue its execution.
Another common place you see it is when people stick the wonderful and useless javascript: on event handlers.
This is a label (the bit ending with a colon) followed by a block (the code surrounded by the curly brackets).
Blocks usually follow control statements, like if(...) { /*block*/ }, but they can also simply stand on their own, as in your example.
Labels allow jumping up several loops at a time with a continue or break; see the linked MDN page for several examples, such as:
var itemsPassed = 0;
var i, j;
top:
for (i = 0; i < items.length; i++){
for (j = 0; j < tests.length; j++)
if (!tests[j].pass(items[i]))
continue top;
itemsPassed++;
}
Here, top: is a label that code inside the inner loop can jump to, in order to escape to the outer loop.
For the sake of anyone who doesn't know what JSON is, and sees a colon in what might actually be an object, and is trying to figure out what it is, and finds this discussion, a colon is also used in JSON. There is a practice of embedding functions in a JSON object. Which might be confusing (As it was to me) for anyone who happens to see this for the first time. (Everyone isn't born with the knowledge of JSON and JavaScript programmed into their brains.) So if you find yourself at this discussion, and you think that every time you see a colon in JavaScript, that it's a label, it might not be. It might be that it's a colon after a label, OR it might be part of JSON. In fact, a colon in JSON being shown as a string, is a lot more common than a label. JSON in the form of an object, will be displayed as [object Object], with all the content hidden. So, unless the JSON is in the form of a string, and you display an object to the console (console.log(object)) all you will see is [object Object]. It is common practice to write JavaScript code, wrapped in an object. In that case you will see the JSON in the form of code. That's when you'll ask yourself, "What is this? and what is that colon for?" Then you'll find yourself at this discussion, and be told that it's a label, when it's really part of JSON. The topic of this discussion is worded: "Please explain this usage of a colon in javascript", and then the "correct answer" is marked as having to do with a label. The correct answer is that a colon can be used in more than one way. So, if you don't know what JSON is, or think you know (like I did, but didn't really understand) read about it here:
JSON.org
That is just a label.
you can use continue [label name] (or break) in a loop to go to a label.
More explanations of what they are can be seen throughout the interwebs.
it is used for labeling an statement in jsvascript.check more detail here.
the labeled statement can be used with break and continue later.

JS bookmarklet issue: Code works in console, fails in bookmarklet

Using a JS bookmarklet to set a custom field in the Wordpress Edit Post screen. The following code works well when I copy/paste it into the console (latest Chrome stable):
document.getElementById('metakeyselect').value = "foo";
document.getElementById('metavalue').value = "bar";
document.getElementById('meta-add-submit').click();
Works without a hitch; I jut paste this into the console, and a new custom var is added to the post (I have "foo" as a var name in WP already).
In bookmarklet form, this same code looks like this:
javascript:document.getElementById('metakeyselect').value = "foo";document.getElementById('metavalue').value = "bar";document.getElementById('meta-add-submit').click();
And it fails: When I click it, the Name and Value boxes are filled in, but nothing gets submitted. The console shows the following error:
Uncaught TypeError: Cannot call method 'click' of null
Any idea why? Same exact code, same browser, same page.
I had a similar problem and am quite sure that's what causes your code to break too.
My minimal example would be the following code on this website (should work afor the entire stackoverflow.com domain):
document.getElementsByName("q")[0].value="foo";
This should write "foo" to the search field (that has no id but is the only element with the name "q"). Both web console and bookmarklet will set the value as expected but the bookmarklet will also change the page to an empty header and a body containing only the word "foo" after a short delay. Assuming that this is not a random bug that only applies to me, the reason for the thrown exception in your example is that the bookmarklet sets the value "foo", then "bar" but changes the content of the web page to "foo", then "bar" before your last line terminates.
Unfortunately I don't know the reason for this behaviour (I found this question looking for that exact information) but that is what most likely causes the TypeError in your excample.
It is possible that the same code runs without any problems when used in a Greasemonkey script (e.g. as the onclick script of a button you added using Greasemonkey).
[Edit:] Apparently, if a bookmarklet evaluates to anything other than undefined, the inner html of the website is replaced by a string representation of that value. To make sure that the bookmarklet evaluates to undefined, you can just type undefined as the last line outside of any condition block. unfortunately that means it is less likely that my assumption toward OP's error is correct but at least future visitors still might find this information usefull.
It looks like the code you use in console works ok.
It seems like the method you turn console code into a bookmarklet is what might result into an error.
The basic IIFE-construction, i.e. Immediately Invoked Function Expression, looks like this:
javascript:(function () {
/*code here*/
})();
Therefore, the code that is supposed to work might be this.
javascript:(function () {
document.getElementById('metakeyselect').value = "foo";
document.getElementById('metavalue').value = "bar";
document.getElementById('meta-add-submit').click();
})();
Does it solve your problem?

IE8 Dot versus Bracket Notation

I'm having a strange issue in IE8 where I'm trying to grab something by simply doing:
window.frames.frames[0].name; // get the name of the inner iFrame object
Nothing fancy, but when script is ran, IE7-8 interpret it like this:
window.frames.frames.0.name;
// which in-turn gives the error
// 'window.frames.frames.0.name' is null or not an object (which is not true)
Why and how is it converting this, and why isn't it even working anymore??
If I type the first one window.frames.frames[0].name; into the console of IE8, it grabs the correct iFrame. But typing in what IE8 interprets (window.frames.frames.0.name;), doesn't work at all... (strangely says, "Expected ';'", which makes zero sense haha.
Anyone ever run into an issue like this?
That dot notation in the error message is just a string the browser uses, poor choice on the browser developers.
The line `window.frames.frames[0].name` does not make sense.
I would expect
window.frames[0].name
or if it is nested frame in a frame
window.frames[0].frames[0].name
window.frames is an array, is it not? Shouldn't you be indexing the first frame?
window.frames[0].frames[0].name;
Does it work if you put parentheses around the the call? like this:
(window.frames.frames[0]).name; // get the name of the inner iFrame object
Also do you really mean do reference window.frames.frames[0] and not just window.frames[0]?
Or do you mean:
window.frames[0].frames[0].name; // get the name of the inner iFrame object

javascript eval issue

I have a function that is parsing xml which contains javascript function calls. An example of this is:
eval(getElementText(PropValue[0]));
getElementText(PropValue[0] = top.hidePopWin()
I have followed this call up to the hidePopWin function and watched it complete from the top of the function to the bottom of the function.
Everything looks in order however I get this pesky error in Firefox: top is null
As you have probably guessed hidePopWin closes the popup window that is currently displayed.
So, hidePopWin is called and it goes through just fine (in fact the popup does in fact close), but after that is the problem. It doesn't go to the next step. I get the top is null message in Firefox (firebug) and it just stops.
The only other thing I need to mention is that this whole process starts on a double click event (legacy code). There is also a single click event that fires as well. At first I thought maybe that was the issue, however, I took out the reference to the onclick event and I still get the same message.
So I'm thinking that it has something to do with the eval statement. Just for more information I am placing a console.log("1") above the eval statement and a console.log("2") below the eval. The "1" prints, the "2" does not.
Does anyone have any ideas as to what might be the issue?
Update:
if(getElementText(PropValue[0]) == "top.hidePopWin();"){
console.log('here');
top.hidePopWin();
console.log('end');
}else{
console.log(getElementText(PropValue[0]));
eval(getElementText(PropValue[0]));
}
OK I tried the above... I see the "here" statement, but it still says top is null. The "end" statement never prints. When I click on the top is null in FF it highlights the eval statement??? So I don't know what the heck is going on.
no, but could you change the code to directly execute the code outside eval and test?
So, change, eval(getElementText(PropValue[0]));
to
top.hidePopWin();
see if you get the same error.
is 'top' visible in that scope if you breakpoint in FF (on the console.log('here') line? It's sounding like there is no such variable (I don't know why the popup closes though).
OK... This may not be the best way to go, but I did finally get it to work. Per the suggestion to change the code to run top.hidePopWin(). I tried those suggestions however I was still getting the top is null issue.
In desperation I took out the "top." and now it works. So I'm guessing there was not a "top" variable (wierd notation in my opinion).
So now I'm capturing if the string is equaling "top.hidePopWin()" and then instead of calling the eval I'm just calling the function hidePopWin();
Seems to work. Let me know if there is another way of going about this.

Strange Javascript statement

if (1) {
google_conversion_value = 1;
}
What is the meaning of the above statement? I mean, this looks like it will always execute so why bother with the if statement?
updated: one reason might be remnants of scripting on the server side. Any other ideas?
updated2: could as easily change the value of the assignment without bothering with the if statement, no?
There are two likely explanations:
It's a leftover from debugging.
The file containing this code is generated dynamically and the original sourcecode contains something like if(<?php echo $some_stuff_enabled; ?>)
However, in the latter case it would have been cleaner to output that code block only if the condition is met - but maybe it's used in some crappy template engine that just allows replacements but no conditionals...
I've seen this before, and I've always assumed it was a remnant of some old condition that was no longer needed, but never removed. I can't see any actual reason to do something like that otherwise.
Potentially because the person writing the code wanted an easy way to turn it off and on again, this is especially useful if there is a lot of code inside the block (not the case here).
Another possibility is that the original programmer couldn't be bothered writing the logic or, more likely, it hadn't been specified so the "if" was left as a placeholder.
More than likely left in from a debug release or something similar. You're right, it will always execute. It could also have been done like this so that it can be easily enabled / disabled by setting the if to 0. Perhaps the developer intended to use it as a flag somewhere else in the code?
actually, this happens when the "if" condition is driven from server, so instead of doing the right thing and not produce the script when the condition is false, they do something like this:
if (<% if (my_server_condition) then Response.Write("1") else Response.Write("0") %>){
// code goes here
}
Perhaps the if statement used to check for a legitimate conditional, and then someone replaced it with a truthy value for testing/debugging/etc.
You're right, it will always execute because 1 is truthy. I would go through your source control history and investigate that line to see if it used to contain a real conditional. If the conditional was always 1, then it's likely a debugging statement. Otherwise someone might have meant for it to be a temporary change, and may not have meant to check that in (which could be bad).
I'm not sure where this code is from, but as you indicated it will always execute. As for why you'd do this, there are times where you want to see what the result of branch code would be, without having to setup an environment. In this case you can comment out the actual value and replace it with if(1) instead for testing:
// if( ... some hard to achieve condition )
if (1) {
// Now you can see what happens if this value is set quickly
google_conversion_value = 1;
}
Of course the problem with this is that it's sometimes easy to forget to remove the if(1) and uncomment the proper condition.
This is actually the javascript recommended by Google on http://support.google.com/adwords/bin/answer.py?hl=en&answer=1722054#nocomments (click on Step 2 for the sample HTML)

Categories

Resources