I want my user to input some text in an input field and click a button "Evaluate" on clicking that button I will convert that inputted text into a JavaScript object if I could and will show all of it's members(properties and functions).
For example if user inputs "document" or "window" I will show all members of document and window respectively.
Iterating through the members of an object is done, but when user inputs some text in input text field and I get that text than that value is treated as String of course how can I convert that text into an object like "document" to document and "window" to window ???
You can use "eval". Edit: Thanks to the comments of #Victor and #Cerbrus for pointing out that eval is unnecessary here. You can also use window[input].
var input = "document";
var obj = eval(input);
for (var prop in obj) console.log(prop + ": " + obj[prop]);
If it's a member of another object (ie, a global object), then you can use the bracket-notation:
var hello = "world";
var variableName = "hello";
console.log(JSON.stringify(window[variableName]));
The proposed solution won't work for sub-properties (ex. window.document.body). I've written a small jsFiddle that should work for most cases. It certainly lacks real error checks but should be a decent place to start http://jsfiddle.net/a6A4m/1/
var showProperties = function(text) {
var output = '';
var object = window;
// if it isn't the global window object
if (text !== 'window') {
var parts = text.split('.');
// Since we're using pop, we need to reverse it first.
parts = parts.reverse();
while (parts.length > 0) {
object = object[parts.pop()];
}
}
$('#content').html(getOutput(object));
};
If you getting input value like that
var selector = $('input').val();
Then the object will be
$(selector)
If your string is JSON format, or the string is a name of javascript object, here a way I saw jQuery.parseJSON do to convert string to object.
var s2o = (new Function("return " +val+";"))();
suppose val contains the value from text input.
It's kind like using Function object as 'compiler', so that you get return a javascript object.
If user pass in document, it give out document object;
if user pass in {id:1, name:"test"}, it give out that object.
Related
I would like to produce a Javascript object which contains a property (onClick example) of type function (myClickHandler example) like this:
var options = {onClick: this.myClickHandler};
I want the object above to be created from a string because the options object can be different every time the app runs and I want it to be evaluated during runtime. (myClickHandler is an existing function). I want the options object created from a string because onClick property can be something else and its function can be something else also. These are determined from the string which is dynamic.
Looking for something like this:
var optionsString = "{onClick: this.myClickHandler}";
var options = JSON.parse(optionsString); //won't work. For illustration only.
This won't work naturally. Ideally, I want to convert the string in one go but I might have to parse it but optionString can contain one or more properties.
Try using eval as :
var myClickHandler = function(){ alert('i am evil'); };
var options = JSON.parse('{ "onClick": "this.myClickHandler" }');
// calling handler now
eval(options.onClick)();
You need some context where the function is bound to, so that you can access the function by key (which can be a string).
let context = {};
context.myclickhandler = () => {
console.log("### It clix ####")
}
let nameOfFunction = "myclickhandler"
let obj = {"onClick" : context[nameOfFunction]};
obj["onClick"]();
In the example the context is just an object , but it could also be the windows object or a instance of a constructor function.
I am trying create a new Anchor tag in Jquery with some attribute and storing it in variable, but when i concatenate it with other variable and append to Dom it gives [OBJECT OBJECT]
JsFiddle for the Same :
http://jsfiddle.net/T8q6T/
var a_name = "Sathwick Rao (sgmdev#gmail.com)^$^4083372345";
var _name = a_name.split('(')[0];
var _part1 = a_name.split('(')[1];
var _email = _part1.split(')')[0];
var htmlElement = $('<a>('+_email+')</a>').attr('href','mailto:'+_email);
$('#shara').html(_name+' '+htmlElement);
You can't concatenate a string with an object like that. Separate the two statements like this:
http://jsfiddle.net/E2Rur/
$('#shara').html(_name).append(htmlElement);
It's because you are trying to concatenate an object with a string. Therefore, the object gets implicitly converted to it's string representation by it's toString function.
E.g.
var div = document.createElement('div');
'some string' + div.toString(); //"some string[object HTMLDivElement]"
'some string' + div; //"some string[object HTMLDivElement]"
If you want to concatenate the outerHTML of the element with some other HTML string that is possible however.
$('#shara').html(_name + ' ' + htmlElement.prop('outerHTML'));
However it's not necessary the most optimal or clean way when it's not necessary.
$('#shara').append($('<span>').addClass('name').text(_name).add(htmlElement));
As you may have noticed, I add the htmlElement to the set and perform a single append operation rather than chaining two append calls. That's to avoid multiple DOM reflows, which are quite expensive.
If you do not want the wrapping span and use the same solution, you can also do:
$('#shara').append($(document.createTextNode(_name + ' ')).add(htmlElement));
To force the variable htmlElement to store a string, I sometimes hack it like this
var htmlElement = $('<a>('+_email+')</a>').attr('href','mailto:'+_email)+"";
$('#shara').html(_name+' '+htmlElement);
These forums are amazing and the contributors I've been helped by are really talented. So I keep coming back everytime I can't solve my own problems or am not understanding a programming concept. This is certainly one of the latter times!
With the help I've received so far, I've managed to develop a complicated form in which the end user will mostly click a series of checkboxes and enter some data into a few textfields. The result of these actions will populate some textboxes with various text, based on the aforementioned actions.
The text that populates the textareas is referenced within a few object literals by each checkbox. This works just fine and the site is quite useable.
In my object literals, I have name:value pairs in which the 'value' is a string of text. I've been trying to include a variable within some name:value pairs to no success. This always breaks the script because the variable is never defined / has a 'null' value on page load.
For example,
Instead of
var example = {
var1:'some string',
var2:'some other string'
}
I tried,
var somevariable = document.getElementById('someId');
var example = {
var1: 'some string' + somevariable + 'some other bit',
var2: 'some other string'
}
My question is whether including a variable referenced elsewhere in the script can be incorporated within the name:value pair in an object literal?
For reference (and because it is a rather long script), my site is: http://www.hematogones.com/bmbiopsies.html.
The trick with an object literal is that it is evaluated immediately; there is no "easy" way to delay the value you get.
var x = "Alice";
var obj = { greeting: "Hello, " + x + "." };
console.log(obj.greeting); // "Hello, Alice."
x = "Bob";
console.log(obj.greeting); // "Hello, Alice."
obj = { greeting: "Hello, " + x + "." };
console.log(obj.greeting); // "Hello, Bob."
Something to come back to later:
If you really really really need to put a variable into a string literal you define later, you could create an inline function. This way, instead of obj.greeting being a simple string, it is a function that you call (which will look like obj.greeting()).This means that instead of the string value being calculated when you declare your object, it will be declared when you call the function. This is a very powerful feature of Javascript called "closures" and you could spend all day learning about the behaviors, expected and unexpected, that you get with them.
var x = "Alice";
var obj = { greeting: function() { return "Hello, " + x + "." }};
console.log(obj.greeting()); // "Hello, Alice."
x = "Bob";
console.log(obj.greeting()); // "Hello, Bob."
The short answer is yes. Here's a working example:
var myStr = "world";
var obj = { var1: "hello " + myStr };
console.log(obj.var1); // Outputs: hello world
As I mentioned in my comment, your specific example has a couple syntax errors, so perhaps just fixing those will correct your issue.
I have a mystery object in Javascript - please could someone tell me how to initialise a similar object?
Background: I've inherited some code that gets passed a params object from Flash. I want to 'fake' the same call, which requires manually constructing the same object. But I can't work out how to take it, because I don't know what type of object it is. (It's not the content that's the problem: it's how to initialise the object.)
Please could someone tell me whether the params object following is an array, a list, a hash or something else - or at least how I can work it out for myself, given that there is no typeof in JavaScript?
function doSomething(params) {
var txt;
for (p in params) {
txt = txt + "param:" + p + ", " + params[p] + "\n";
}
return txt;
}
Thanks!
This will alert the type of 'params'.
function doSomething(params) {
alert("Type of params variable: " + typeof params);
var txt = '', p;
for (p in params) {
txt += "param:" + p + ", " + params[p] + "\n";
}
return txt;
}
If you just want to intercept the variable, and pass the param to the original function, try this:
window.originalFunction = doSomething;
window.doSomething = function(param1){
// do something with param1
return window.originalFunction(param1);
};
To check whether params is an array or not, try:
alert(params instanceof Array);
You can think of it as a hash. In your example, p is the property name and params[p] accesses the value of that named property.
And, as usual, Pekka is right. There most definitely is a "typeof" operator in Javascript. I don't know where you got the idea that there isn't.
From the looks of it, params looks like a dictionary
There are no lists, hashes, dictionaries (etc.) in JavaScript. There are only objects and arrays (and arrays are a type of object).
Given that the code uses for... in, it looks like it would be an Object. That is, a container with named members. Beyond that, it depends on how the object was initialized.
If you would like to make a copy of the object, try using its prototype:
var copy = {};
copy.prototype = params
Here's the problem - I know function by name (and that function has already been loaded form an external script), but I don't have an actual function object avail for me to call. Normally I would call eval(function_name + "(arg1, arg2)"), but in my case I need to pass an object to it, not a string.
Simple example:
var div = document.getElementById('myDiv')
var func = "function_name" -- this function expects a DOM element passed, not id
How do I execute this function?
Thanks!
Andrey
Never use eval, it´s evil (see only one letter difference)
You can simply do:
var div = document.getElementById('myDiv');
var result = window[function_name](div);
This is possible because functions are first class objects in javascript, so you can acces them as you could with anyother variable. Note that this will also work for functions that want strings or anything as paramter:
var result = window[another_function_name]("string1", [1, "an array"]);
You should be able to get the function object from the top-level window. E.g.
var name = "function_name";
var func = window[name];
func( blah );