I have an Object and I'm trying to use jquery to quickly change the parameter values, but the parameters keep coming back null. code brings back the list of parameters but I can't seem to change anything. Even if I put it at it's base of parameters to change everything - it still comes back as null.
Other than that it works, but if u look closely you will see some api error messages in black at the top left. I added a pastebin so you can see what I'm doing.
http://jsfiddle.net/f4qMe/
and below is the javascript I'm running to try and change the objects parameters. The object is called (id) twitchTV.
function test(){
var data = "http://www.twitch.tv/widgets/live_embed_player.swf?channel=day9tv";
var src = "hostname=www.twitch.tv&auto_play=true&start_volume=25&channel=day9tv";
var code = $("#twitchTV").html();
var newcode = $("param", code).attr("value", src).html();
$("#twitchTV").html(newcode);
$("#twitchTV").attr("data", data);
}
Your problem is probably here:
var code = $("#twitchTV").html();
var newcode = $("param", code).attr("value", src).html();
html() returns a string so code is a string and you're using it as context in newcode which expects an DOM element or jquery object instead.
Related
I happened to have super dumb issue and I'm stuck.
I do console.log(data) and I get exactly this:
<a href='http://www.someurl.com'>caption</a>
The question is how do I get this links "href" attribute.
I have absolutely no idea why, but these doesn't work:
data.text() == Uncaught TypeError: undefined is not a function (should be: caption)
$('a',data).attr('href') == undefined (should be: http://www.someurl.com)
Maybe this is not a string, but object or something else? How to check that? My JS looks like this:
window.send_to_editor = function(data) {
var videourl = data;
console.log(videourl.text()); // Uncaught TypeError: undefined is not a function
console.log(videourl); // <a href='http://www.someurl.com'>caption</a>
}
Using jQuery, you can do something like that:
var data = "<a href='http://www.someurl.com'>caption</a>";
var link = $(data).attr('href');
It will create dynamically your DOM element, then you will be able to get your attribute href.
You should first find out, what type data is. To do this you can use the JavaScript builtin function typeof(data).
It's not a jQuery object. That is why it is undefined. First, create a jQuery object.
var _videourl = $(videourl);
console.log(_videourl.text());
console.log(_videourl.attr('href'));
// caption (index)
// http://www.someurl.com
DEMO
In your case, data is a string, not a jQuery object and therefore does not have of jQuery's methods (like text).
If you are certain that data is a string containing a link, you can use a regular expression to extract the link like so:
var match = data.match(/href='(.*)'/g);
url = match && match[1];
console.log(url);
Alternately, you can create a jQuery object from your string. But that's a much more expensive operation if you just want to get the url.
In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.
I have a JSON string which includes a function I need to call.
My JSON looks like this:
{
"type":"listview",
// the function I would like to call
"content":"dynoData.getRetailers()",
"custom_classes":["","nMT pickList","",""],
"lib":"static_listview.html",
"tmp":"tmp_listview_inset",
"lang":"locale_search",
...
I'm using this to assemble a jQuery Mobile listview on the client. To get the dynamic data, I need to call dynoData.getRetailers().
However I'm struggling to make the call :-)
This is what I'm trying:
var dyn = $.parseJSON( passed_JSON_string ),
content = dyn.content;
I had hoped calling it would trigger the function but it just returns the function name as a string.
Question:
How can trigger the actual function?
Thanks!
EDIT:
I'm putting the JSON string on the HTML element on the actual page, which I will replace with the element I'm building. Here is the HTML:
<ul data-template="true" data-config='{
"type":"listview",
"content":"dynoData.getRetailers()",
"custom_classes":["","nMT pickList","",""],
"lib":"static_listview.html",
"tmp":"tmp_listview_inset",
"lang":"locale_search",
"theme":"c",
"filter":"true"
}'></ul>
I could put all of these into data- attributes, but that would be messy...
Solution:
This worked:
1) change JSON to:
..."method":"getRetailers", ...
2) call from Javascript:
content = dynoData[ dyn.method ]();
Thanks everyone!
Assuming the function is always part of the dyn object you can use notation like following to call a function:
dyn['dynoData']['getRetailers']();
So if you are able to adjust json you could send back something like:
"content":{ "mainObject": "dynoData" , "method" :"getRetailers"}
And translate it to your dynamic function using variables:
dyn[content.mainObject][content.method]();
As an example using jQuery try using the following :
$('div')['hide']();
Which is the same as :
$('div').hide()
As charlietfl pointed out you can use object notation to call functions. For your case you have to get rid off () and split it, then call it like this;
jQuery(function($) {
var temp = $('ul').data('config').content.replace(/\(\)/g, '').split('.');
window[temp[0]][temp[1]]();
});
However this could solve your problem, if you think about future, you have to extend it a little bit. This way even you don't know the depth, you can call it anyway;
jQuery(function($) {
var temp = $('ul').data('config').content.replace(/\(\)/g, '').split('.'), func, i, il = temp.length;
for(i = 0; i < il; i++) {
if(func == null) {
func = window[temp[i]];
continue;
}
func = func[temp[i]];
}
func();
});
Try ConversationJS. It makes dynamic calls pretty easy and its a great way to decouple your codebase: https://github.com/rhyneandrew/Conversation.JS
JSON is purely data notation to be passed around so it is easily read and parsed, therefore it has no concept of functions. However, there are other ways of dealing with this and if you are starting to think that that is the only way to deal with your dilemma, then take a step back and examine your design. Instead of using this:
eval(yourCode);
Try this
var tempFun = new Function(yourCode);
tempFun();
I need to pass a jQuery object in to a workaround for an eval. The issue is that i need access to a jQuery object that is out side the eval area but i can't see to pass it in. here is what i have.
var jObj = $(selector);
var myCode = "var jObj="+jObj+"; var i="+i+"; "+shape.mouseover.onEnd.replace("\u0027","'");
var myFucn = new Function(myCode);
myFucn();
the oject I'm getting the string out of is
shape.mouseover.onEnd.replace("\u0027","'");
is working and what I'm passing in that string is
open_info(jObj,i)
Which is what i have to fire. The deal is that the code is run thru YUI compressor so the jObj var becomes something else so i need to pass that in. Right now i get an error where it thinks it should have and ending ] which is not right. I is working it seems, just not the jObj var.
EDIT
there are many way to get where i need to be that are close but not quite like
How to pass parameters in eval in an object form?
shape.mouseover.onEnd = "open_info(jObj,i)";
/*
* this is coming in and must be as it is, don't say it's wrong please
* it's not able to be done anyother way!
*/
//lets process the string and pull in the vars
/* BEOFRE YUI COMPRESSOR CHANGES THINGS and works!!!
var jObj = $(selector);
var i = 1;
var myCode = shape.style.events.mouseover.onEnd.replace("\u0027","'");
var myFucn = new Function(myCode);
myFucn();
*/
// AFTER note it can be random as i change code so it fails cause
// var jObj is now var r and var i is now var e
var r = $(selector);
var e = 1;
var p= shape.style.events.mouseover.onEnd.replace("\u0027","'");
var f= new Function(p);
f();
Now it works before the compression.. After is not due to the change. Hope tha tclears it up some
I might be going down the wrong tracks and be confused here..
But isnt this what your trying to do?
Send myFucn the correct object and what ever i is
myFucn($(selector),10);
function myFucn(jObj,i)
{
shape.mouseover.onEnd.replace("\u0027","'");
}
I still don't understand why this question got 2 down votes, but well it's solved and works great. The trick is to do the same manipulation of the dom state. It's really simple once it is placed out.
//so this is what the object is parsed out to from the json string
//since you can't just pass a function stright that way any how
shape.mouseover.onEnd = "open_info(jObj,i)";
//this is what will take that string and process it
//note jObj is what is in the orgain code but it changes to
// var r or something else that is shorter after going thru YUI compressor
// Which is why we can't just use open_info(jObj,i) and it work..
// ie: it's not an issue with scoope but an issues with var names being shortened
(function(){
//this is the trick on passing them so YUI doesn't get them
//use a string and YUI skips it so we directly create the
//needed oject in the window namespace
window['jObj']=jObj; window['i']=i;
var p= shape.mouseover.onEnd;
var f= new Function(p);
f();
})();
That is it.. I put it in a click or hover event so it's kin to an onClick.
/* EXMAPLE OUTPUT AFTER YUI COMPRESSION
//Note after the YUI compressor get ahold of that
//processing code above it'll look like
*/
function(){window.jObj=n,window.i=t;var u=i.mouseover.onEnd,r=new Function(u);r()}();
So the way that works is, I needed to fix the issue of the var jObj being renamed. So I simply made a sting for the name and let the compressed the var name fill the name of the object I need for the processed code string. Don’t know why I didn’t see it before and I would have saved my rep value :-\ .. oh well. May be a way to shorten this but I'm leaving it for now.
Edit
I recant the edit it was working. :) Very well.. Left wondering what any other ways there would be to make it do the same thing.
I am customizing Denis Gritcyuk's Popup date picker.
This pop-up script uses inline Javascript in a href link, to set the selected date into the input field, in the parent window, that is was called for. An example URL looks like:
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.close();">3</a>
The input field name, (e.g. document.formname.field), is passed to the script as a string parameter.
I would like to add things done when that link is clicked (e.g. change background color of field, set flag, etc.). So while this DOES work, it's getting ugly fast.
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.opener.document.formname.field.style.backgroundColor='#FFB6C1';
window.close();">3</a>
How would I move these inline commands into a JS function? This would give me much cleaner URLs and code. The URL would now look something like
3
with a function like (this example obviously does NOT work):
function updateField (str_target, str_datetime) {
var fieldName = "window.opener" + str_target;
[fieldName].value = str_datetime;
[fieldName].style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
So any suggestions on how this can be done, please?
I'd prefer to hide the dom path tracing back from the current window back to the opener. It's appropriate to bake that into the function since the function will always be used in the context of that child popup. Then your function call is cleaner and more readable. Obviously, replace "myField" with the ID of the field you're intending to update.
3
function updateField ( str_date, str_fieldname ) {
var fieldToUpdate = document.getElementById( str_fieldname );
fieldToUpdate.value = str_date;
fieldToUpdate.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
You're acessing the property incorrectly. Try:
function updateField (str_target, str_datetime) {
var fieldName = window.opener;
str_target = str_target.split('.');
for (var i = 0; i < str_target.length; i++)
fieldName = fieldName[str_target[i]];
fieldName.value = str_datetime;
fieldName.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
The bracket notation ([]) is only used for properties of objects, not objects themselves. If you found my post helpful, please vote for it.
You can build a string and evaluate it as code using the eval function, but I would recommend against it.
There are a couple of things wrong with your code:
You cannot use the [] operator in a global context, you have to suffix it on an object, so you can say window["opener"] and this will be equivalent to window.opener, but there is no such thing as simply ["window"]
When navigating nested properties, as in window.opener.document you cannot navigate multiple levels using the [] operator. I.e. window["opener.document"] is not allowed. You must use window["opener"]["document"] instead.