Can I use ui:repeat inside h:outputScript? - javascript

Or how would I convert a list of SelectItems to a JavaScript array?
Currently I am trying this:
<h:outputScript>
<!-- Trailing commas valid as per http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5 -->
var possibleOption = [<ui:repeat value="#{bean.mySelectItems}" var="selectItem">"#{selectItem.value}",</ui:repeat>];
var firstOption = possibleOption[0];
</h:outputScript>
And it works, except that firstOption is undefined although possibleOption gets correctly populated when I check in the console. Maybe a timing problem? Is this even valid JSF, and if so, is there a "blocking" version of ui:repeat or something?
Or which other approach would you recommend?

Aaaah, I got it:
actually I was using:
var chosenOption = '#{empty bean.chosenOption ? possibleOption[0] : bean.chosenOption}';
Which is (now) of course wrong, because I was using possibleOption[0] inside the EL expression headbang
Sorry, one should always post the actual code I guess, not some dumbed down showcase ;)

Related

SyntaxError: identifier starts immediately after numeric literal?

I have been working on my project where I had to do some updates on my data records. After I finished my update I got an error: SyntaxError: identifier starts immediately after numeric literal and this line of code was below that error in firebug : maxScores.ew-19a = ''
I looked up in my code and I found where is this output coming from, here is the code:
var maxScores = new Object;
<cfoutput query="getRec">maxScores.#LCase(tCode)# = '#maxScore#';</cfoutput>
In my update I had to put - symbol between letter and number, in old data I did not have that so I think that causing the problem here. I was wondering how I can prevent this or if there is any method that I have to put around my output to prevent this? If you know how this can be fixed pleas let me know. Thank you.
ColdFusion will attempt to subtract ew from 19a when you just dump it between to pound signs like that. You will need to use bracket/object notation here. Try this:
<cfoutput query="getRec">
maxScores.#LCase(getRec["tCode"][currentrow])# = '#getRec["maxScore"][currentrow]#';
</cfoutput>
If you want to Lower case something do it in the query. Outputing JS using CF is useful and solves many problems, but you want to keep it as clean as possible to keep your brain from fogging over. :)

Can't access object in jquery (prevObject?)

A function in my WP plugin has just randomly (as far as I can tell) stopped working.
Here's the code in question:
window.send_to_editor = function(html) {
var classes = jQuery('img',html).attr('class');
var items = classes.split(" ");
... more stuff here
}
I've confirmed that the html variable is indeed an img html tag. Here's what firebug shows when I do a console.log of the object (console.log(jQuery('img',html));):
Object[]
context -> undefined
jquery -> "1.11.2"
length -> 0
prevObject -> Object[img.alignnone.size-full.wp-image-1234 name.jpg]
And the error it shows is classes is undefined.
I figure there's something wrong with the object I get, but this used to work recently and I'm not aware of any changes in the site that could have caused this.
I'd appreciate any input on this.
EDIT:
More info. This happens with two plugins which are supposed to be unrelated (made by different people). It happens when, after uploading an image to the server (or selecting a previously uploaded picture) you try to insert it into the post.
As I said before this error has appeared out of nowhere, it was working as intended a couple days ago. The only thing I can think of that has changed since then is the domain name, but I can't see how that could be related.
The jQuery selector always returns a jQuery object, but when the length is 0 then no elements were found matching the selector that you provided. In your example you've confirmed that nothing is selected as the length of the jQuery object is 0. Perform a check whether an element was selected like this:
var $els = jQuery('img',html),
classes;
if ($els.length) {
classes = $els.attr("class");
}
Keep in mind that your DOM query is limited by what you pass in as the html parameter. If you simply want to find the images on the page do: var $els = jQuery('img');
I finally managed to fix this; the key was parsing the html string variable into proper HTML, using jQuery.parseHTML(). Thanks to everyone who helped!

Why isn't my array index displaying?

This seems so simple and I honestly can't see why this isn't working. Looked at other answers on here and mine still isn't working.
var randomArray = new Array();
randomArray[0] = 859;
alert(randomArray[0]);
How come nothing happens? It's probably an easy answer but I can't work it out.
Also, I'm trying to work out how to put a random number in the array so rather than putting 859 in index 0 lets say I want to put a random number between 1 and 20 in, so far I've got this but thats not working either
randomArray[1]=Math.floor(Math.random()*3);
EDIT: the .toString on alert seemed to fix it, thanks guys, knew it would be something small!
Is your javascript being referenced properly in a script tag with the correct type set?
<script type="text/javascript" ...> </script>
If not, it's fully possible your browser is simply ignoring it.
This is a wild guess, because your question doesn't contain enough information to know for sure, but make sure that your code is in a <script> block that looks like this:
<script>
// your code
</script>
Get rid of any "type" or "language" attribute on the tag; they're not needed and they're a source of error. If the "type" value is mispelled, then the browser will completely ignore the code.
Try calling .ToString() on your array property.
alert(randomArray[0].toString());

How to pass value to using external variable in javascript?

following code works properly
draw([['Rice',20,28,38],['Paddy',31,38,55],]);
but when i try using external variable like
var val1=20;
var val2=30;
var val3=40;
draw([['Rice',val1,val2,val3],['Paddy',31,38,55],]);
It wont work.
Just showing that your example code works fine using the Firebug console. Can you post more of your code? Your stripped-down example is probably missing something else that's causing a problem.
What is your draw() function doing? Could something in that function be breaking?
EDIT: Another problem could be the trailing comma after your second array. That will throw an error in Internet Explorer.
alert([['Rice',val1,val2,val3],['Paddy',31,38,55],]);
should be:
alert([['Rice',val1,val2,val3],['Paddy',31,38,55]]);
That may solve your issue (though you also have that in your 'working' example, but I thought it worth mentioning).
Your code snippets are not equivalent -- the second one has different values (['Rice',20,30,40] vs ['Rice',20,28,38]). Other than that, they are equivalent and should have the same effects.

Escaping dilemma in Javascript

I have the following
var id='123';
newDiv.innerHTML = "";
Which renders in my HTML.
The problem I have is that I wish to take the call to the method TestFunction, and use as a string parameter in my function StepTwo(string, boolean), which would ideally end up in live HTML as shown...
notice how the TestFunction is a string here (it is executed within StepTwo using eval).
I have tried to format my JS as by :
newDiv.innerHTML = "";
but while this appears to me correct in my IDE, in the rendered HTML, it as garbelled beyond belief.
Would appreciate if anyone could point me in the right direction. Thanks!
One of the biggest capital failures on the internet is creating html in javascript by gluing strings together.
var mya = document.createElement("a");
mya.href="#";
mya.onclick = function(){
StepTwo(function(){
TestFunction('123', false );
}, true );
};
newDiv.innerHTML = "";
newDiv.appendChild(mya);
This Eliminates the need for any fancy escaping stuff.
( I probably should do 'onclick' differently, but this should work, I'm trying hard not to just use jQuery code to do everything )
Heres how I would do it in jQuery:
jQuery(function($){
var container = $("#container");
var link = document.createElement("a"); /* faster than $("<a></a>"); */
$(link).attr("href", "Something ( or # )" );
$(link).click( function(){
var doStepTwo = function()
{
TestFunction('123', true );
};
StepTwo( doStepTwo, false ); /* StepTwo -> doStepTwo -> TestFunction() */
});
container.append(link);
});
There is no good excuse for gluing strings together in Javascript
All it does is ADD overhead of html parsing back into dom structures, and ADD potential for XSS based broken HTML. Even beloved google get this wrong in some of their advertising scripts and have caused epic failures in many cases I have seen ( and they don't want to know about it )
I don't understand Javascript is the only excuse, and it's NOT a good one.
Try using " instead of \"
newDiv.innerHTML = "<a href="#"...
You should be using " not " or \" inside an HTML string quoted with double-quotes.
NewDiv.innerHTML = "";
There's probably a better way to do this - any time you find yourself using eval() you should stand back and look for a different solution.
You claim that eval is the right thing to do here. I'm not so sure.
Have you considered this approach:
and in your StepTwo function
function StepTwo(func,args,flag){
//do what ever you do with the flag
//instead of eval use the function.apply to call the function.
func.apply(args);
}
You could create the a element and attach to the click event using DOM Methods.
A Javascript Framework (like the ubiquitous jQuery) would make this a lot easier.
Your biggest problem is using eval, it leads to so many potential problems that it's nearly always better to find an alternative solution.
Your immediate problem is that what you really have is
as the next " after the start of the onclick attribute, closes it. Use " as others have suggested. And don't use eval.
You need to alternate your " and '.
Maybe you don't need quotes around the 123, because of Javascripts flexible typing. Pass it without quotes but treat it as a string within TestFunction.
Hey guys, thanks for all the answers. I find that the quot; seems to work best.
I'll give you guys some votes up once I get more reputation!
In regards to eval(), what you see in the question is a very small snapshot of the application being developed. I understand the woes of eval, however, this is one of those one in a million situations where it's the correct choice for the situation at hand.
It would be understood better if you could see what these functions do (have given them very generic names for stackoverflow).
Thanks again!
The best way is to create the element with document.createElement, but if you're not willing to, I guess you could do or use ".
In your code:
newDiv.innerHTML = "";
If it doesn't work, try changing "\'" to "\\'".
Remember that the " character is used to open and close the attribute on HTML tags. If you use it in the attribute's value, the browser will understand it as the close char.
Example:
<input type="text" value="foo"bar"> will end up being <input type="text" value="foo">.
...
I know this is hella' old now, but if anyone has issues with escaped strings when using eval (and you absolutely have to use eval), I've got a way to avoid problems.
var html = '';
eval('(function(div, html){div.innerHTML = html;})')(newDiv, html);
So, what's going on here?
eval creates a function that contains two parameters, div and html and returns it.
The function is immediately run with the parameters to the right of the eval function. This is basically like an IIFE.
In this case
var myNewMethod = eval('(function(div, html){div.innerHTML = html;})');
is basically the same as:
var myNewMethod = function(div, html){div.innerHTML = html;}
and then we're just doing this:
myNewMethod(newDiv, html); //where html had the string containing markup
I would suggest not using eval. If it can't be avoided, or if you control all the inputs and there's no risk of injection then this will help in cases where string escapes are an issue.
I also tend to use Function, but it isn't any more secure.
Here's the snippet I use:
var feval = function(code) {
return (new Function(code))();
}

Categories