JQuery: parameter: hard-coded string vs ajax retrieved string - javascript

I am trying to get the JQuery Token Input prepopulated.
var assignUserJson=$('#assignUserJson').val();
console.log(assignUserJson); //[{"id":"1","name":"Andrew"},{"id":"3","name":"John"}]
Here is a difference between two ways that I supposed it should work in:
$('#assignTask').tokenInput('/users/suggest', {prePopulate: assignUserJson}); // doesn't work
And this works:
$('#assignTask').tokenInput('/users/suggest', {prePopulate: [{"id":"1","name":"Andrew"},{"id":"3","name":"John"}]}); // works
Why is that? Shouldn't I be able to get the value from a hidden input field and pass it to the tokenInput function?

In your first method, assignUserJson is a string whereas in the second method, it is an array object. Objectifying the first one should work:
$('#assignTask').tokenInput('/users/suggest', {prePopulate: JSON.parse(assignUserJson)});

With the first method you're passing a JSON string, not a tangible JS object as you are in the second.
You would first need to parse the JSON. This can be done natively in ECMA5 or, for older browsers, via third-party support.
$('#assignTask').tokenInput('/users/suggest', {prePopulate: JSON.parse(assignUserJson)}); // doesn't work

Related

getComputedStyle Font Family returns multiple families [duplicate]

Hi I have an object rowObject passed into a javascript function. When I inspect it by putting it into an alert I see something like:
435,345,345345,56456
What I want to achieve is to get the first integer ie. 435 from the list.
I know how to do this in server side code but client side code.
Can someone please help me with this?
Assuming that your rowObject is a string, you can use .split() to split the comma delimited list. At this point you can access the array of items by index and get the first element.
http://www.w3schools.com/jsref/jsref_split.asp
An Example
var rowObject = "435,345,345345,56456";
var splitRowObject = rowObject.split(',');
if(splitRowObject.length > 0)
alert(splitRowObject[0]);
alert() is calling objects toString() method, so you don't know the structure of the object. It is a good idea to use console.log instead for logging objects as in modern browsers it will allow you to explore structure of the object in the console window.
One of the solutions you can do without knowing the structure is:
var firstInteger = +rowObject.toString().split(',')[0] // 435
That works if rowObject is string, array or everything else :).
EDIT: Putting + before the string will try to convert it to a number.
Have you tried rowObject[0]?
The fact that the alert shows 435,345,345345,56456 doesn't mean that the object is string, it could be Object and Array as well as their toString method implemented to display it in such way. For example the native array is also looks like that when alerting or converting to string, so you need to call toString method at first then split it by comma:
var firstInt = rowObject.toString().split(',')[0];

Strings not formatted in Node.js after a non-string

Is the following a bug or a feature in Node.js? If it is a feature, please point out at the spec.
When we call this:
console.log('one\ntwo', 'three\nfour');
we get the expected:
one
two three
four
But if we use a non-string value in front of it, then strings are no longer formatted as expected:
console.log(1, 'one\ntwo', 'three\nfour');
outputs:
1 'one\ntwo' 'three\nfour'
Why is that?
UPDATE
From the link by #MuliYulzary, it would appear that it is supposed to set the formatting, based on whether the first parameter is a string or not.
I found out, that when the first parameter is a string, Node.js uses util.format(parameters), and when the first parameter is not a string, it uses util.inspect.
That's how it works.
From the document console.log, it works correctly
console.log(object [, object, ...])
Logs a debug level message. You pass one or more objects to this method, each of which are evaluated and concatenated into a space-delimited string. The first parameter you pass to console.log() may contain Format Specifiers.
See the sample usage here

What is the right way to store JavaScript source code in a json object?

I want to edit JavaScript in a textarea and store it back into a JavaScript object. For example I have this object:
var item1 = {
'id' : 1,
'title':'title',
'sourcecode' : "alert('hallo')"
};
If I would change the content to alert("hallo") or a even more complex example does this break my object?
I would think there is some escape function like this https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/escape. But it is marked as deprecated.
So if this is deprecated what would be the right way for storing complex JavaScript code into a JavaScript object?
Should I use stringify ?
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The JSON.stringify() method converts a JavaScript value to a JSON
string, optionally replacing values if a replacer function is
specified, or optionally including only the specified properties if a
replacer array is specified.
This does not read like there is an automated escape build in.
If you need to send the data to a server, I'd say you should encodeURI your sourceCode, and then JSON.stringify the entire object. When retreiving data from the server, you should decodeURI the sourceCode

append object to innerHTML and get that object from innerHTML

here is an example in jsfiddle.
I want to know if I can append a javascript object to innerHTML, that get that object again from innerHTML as object.
something like,
alert((this.innerHTML).html);
that's just an example, don't ask me why do you need this?
I'm trying to edit an existing code, and I have to do this so.
I have to transfer an object via div.innerHTML.
Check this jsfiddle. In it, I add the object to the div as a 'data-'-attribute, using JSON to convert it to a string. After that, adding some comment to the div triggers the DOMSubtreeModified-handler, in which the 'html'-part of the object is retrieved and alerted. It that something to work with?
In this case, quite possible your only option is to convert your object to string and then put that into the element. (This is done by looping through the key, values building the string as you go.)
You would reverse the process to convert it back into an obj.
I know some javascript libary's have helper functions to make this process very simple.
You could try adding the data directly onto the dom element, rather than as its content..
tempDiv.objData = myObject;
It was suggested to use JSON, but no code. So:
function addObjAsJSON(el, obj) {
el.setAttribute('data-myJSON', encodeURIComponent(JSON.stringify(obj)));
}
function getObjAsJSON(el) {
return JSON.parse(decodeURIComponent(el.getAttribute('data-myJSON')));
}
That should allow you to add anything as a serialised object, then get it back. You should add some error checking to make it robust though (e.g. check that you get a string back from the call to getAttribute).
For user agents that don't have built-in JSON support, see json.org which has a link in the javascript section to json.js.

passing a variable into a json collection

I'm trying to call the following js method. I wish to pass in the variable siteid. I can alert this value. But it doesn't seem to work in the following context. ie if just add the id 1234 it works.
alert(siteid);
embedSWF ('flashcontent', '{"siteID":siteid,"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}');
You need to concatenate the value of siteid into your string: '...' + siteid + '...'
Depending on what you're building, you may want the string to have quotes around the value.
The most robust way to do this is to first make the object as a normal object and then serialize it:
var parms = {siteID: siteid, siteType: "portal", ...};
embedSWF('flashcontent', JSON.stringify(parms));
If you need to support outdated browsers that don't have the built-in JSON object, there are several implementations available online.
embedSWF ('flashcontent', '{"siteID":'+siteid+',"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}');
You're passing a string:
'{"siteID":siteid,"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}'
You probably mean to pass:
'{"siteID":' + siteid + ',"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}');
It seems a little weird to pass a JSON string, rather than the associative array itself. Either way, that's your problem, above.

Categories

Resources