JavaScript - passing string as an object property - javascript

Just FYI this code is part of ExtJS 4 script. I have a global setting which I use to show the path to the dir where my icons are. I'm making some modifications so before was:
g_settings.iconUrl
but now I need to pass a third argument property like this:
g_settings.iconUrl.docIcon
The problem I met is where I have an if statement where I check for different values:
if (extensions == 'doc'||extensions == 'docx'||extensions == 'xlsx'||extensions == 'xls)
and then I do:
extensions += 'Icon';
and I need to use:
g_settings.iconUrl.extension
when I use console.log(extensions) it's value is as expected (for example docIcon) but when I try to use it as a property it doesn't work. If I use console.log on:
console.log(g_settings.iconUrl+ '.' +extensions)
the output is [object Object].docIcon so I think I have to convert somehow extensions to object too.
I'm not sure that this will solve the problem but that's what I have for now.
Any suggestions?
Thanks
Leron

Why not just add it to the string..
console.log("g_settings.iconUrl." + examples)

iconURL was (and probably still is) a string, but then you added some properties... so on the assignment of .iconURL="..." you should use
iconURL.file="...";//(or other name you choose)
and latter use
.iconURL.file+"."+extensions;

Related

check for undefined not working

I just started programming with javascript no long ago. But I am still confused with the way it handles arrays.
the problem is that I have an array in which there some content as undefined. I want to check for those undefined values and escape them. How do I do it. the following code is not working and I have not found a way to solve this problem.
if(myarray[0]!=='undefined')
if(myarray[0])!='undefined') // I have also tried
if(myarray[0]).search('undefined')==(-1)) // and also this
however none of these options is working. I could see when debugging that the value in the array is 'undefined' but the condition is never met. once again my aim is to do something when it is not undefined. please how could I do it. I found a similar question Test if something is not undefined in JavaScript but it does not work
You are comparing undefined to 'undefined', which is a string so its different. You need to compare like this:
myarray=[undefined];
if(myarray[0]!==undefined){
console.log(4)
}
juvian provided a good answer. You need to use undefined instead of 'undefined' because you are comparing your array to a string.
On my current project, I use underscore to check for undefined. It's pretty simple and straight-forward.
var array = [];
if (_.isUndefined(array));
http://underscorejs.org/#isUndefined
You're comparing the myarray[0] value to a string value of undefined.
What you need is this:
if (typeof(myarray[0]) !== 'undefined')
Hope this helps!
You should check it as follows: if(typeof(myarray[0]) != 'undefined')

JSON return error as undefined when the value is numeric

not sure where the errors lies in what I am trying to achieve.
I am working with someone else's code and unfortunately they have used numbers for div ids in some places.
These number ids are used in various places and if I can, I want to find a way to keep things as they are.
So,
returning the following in JSON:
editorID: "1000"
And in my AJAX call i use that return like so:
var editorID = response.editorID;
CKEDITOR.instances.editorID.insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');
However this gives me an error saying that the editorID is undefined.
As you can I already use a JSON response in my code, this works fine so its not a problem with datatypes etc.
I also tried to do:
alert(response.editorID);
which gave me the correct value.
When I tried putting a number directly into CKEditor insertHTML code it was showing my syntax errors so maybe thats the issue. If so, any work around for it?
Thanks. Craig.
To use a variable as a property, you have to use [] notation:
CKEDITOR.instances[editorID].insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');
When you use .editorID, it's looking for a property named editorID, not 1000.
You also have to use this syntax when the property isn't a valid identifer. So if you wanted to put the number directly, you would write:
CKEDITOR.instances['1000'].insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');

Javascript json, check all keys for undefined ('null') and set default

Firstoff I'd like to add I've been learning javascript for like only 2 days now. I'm pretty much way ahead of myself with what I'm trying to get but here goes.
I have a json array from which I get data to replace/insert in my page. The first problem I have is that if it comes across an empty ('null') key it will just stop. Will not even try to continu.
document.getElementById("id1")src=json.img1.link;
document.getElementById("id2")src=json.img2.link;
document.getElementById("id3")src=json.img3.link;
json.img2.link is empty ('null' response from json.). javascript will then not replace "id2" but it also won't replace "id3".
I'm now trying to find a solution where it will if nothing else at least set a default.
The script is not continuing executing because it comes to an error --trying to access property link of an undefined object
Try
document.getElementById('id2').src = json.img2 ? json.img2.link : 'defaultLink';
This way your are checking for undefined (ie null) object in img2 and assigning the default value. This assumes that what is not defined (null) is the img2 object.
Actually I don't think your code should work at all, you are missing the. before the src So, try
document.getElementById("id1").src=json.img1.link;
document.getElementById("id2").src=json.img2.link;
document.getElementById("id3").src=json.img3.link;
and let us know if that doesn't solve the problem.
Btw, +points for learning JavaScript and not just straight into jQuery!

Why is 'indexOf' not returning anything?

The book I am reading tells me to open up the JavaScript console and try the code "foo: bar".indexOf(":"). I've tried it in many ways. I tried removing quotation marks, putting it inside a show() and alert() function. I just can't seem to tease anything out.
Has something changed in JavaScript? Has the author made a mistake? Am I supposed to get no return? Do I need to append document.write, perhaps? Any help greatly appreciated.
Yes something changed in Firefox 5+
However the console (ctrl-shift-k) still works
In the error console (ctrl-shift-J) you will need to wrap it in alert:
foo:bar is a property definition in json, and indexOf is supposed to deal with a left value (string variable, constant, or at least something that can have characters in it. I don't know why the book you are reading wants you to do this, but it doesn't seem to be correct. The correct way to use indexOf would be :
var myObject = {
foo:"bar"
}
alert(myObject.foo.indexOf("a"));
try like follows, it should work. Generally the indexOf() will return -1 if the value to search for never occurs.
var str="foo:bar";
document.write(str.indexOf(":") + "<br />");
The output should be 3

jQuery 1.3 - Issue with Setting an Attribute Value

This is my first stackoverflow question, so try to be nice. ;-D
My issue is this, I am refactoring some existing javascript code and using jQuery to do it. In several places I've come across javascript code similar to the following:
// some js code working with the customAttribute value
javascriptElementObject.customAttribue = void(0);
The javascriptElementObject is now a jQuery object and I have been attempting to use the following code to do the same thing:
// some js code working with the customAttribute value
javascriptElementObject.attr("customAttribute", void(0));
However, this does not seem to be doing anything. The following code works however:
javascriptElementObject.get(0).customAttribute = void(0);
I'm aware of jQuery's removeAttr() function, but have not used it so far because I don't know if it's equivalent to setting the attribute value to void(0).
So I guess that really means I have 2 questions:
Why doesn't the first jQuery version work?
Are .get(0).customAttribue = void(0); and .removeAttr("customAttribute); equivalent?
Thanks.
jQuery likes to overload its methods so:
obj.attr( name ) //retrieves the attribute value
obj.attr( name, value ) //sets the attribute
obj.attr( name, void(0) ) == obj.attr( name, null ) == obj.attr( name ) //i.e retrieving the attribute
You might want to try the following if you want to set an empty attribute
obj.attr( name, '' )
This will also apply to other methods jQuery.html() for example
What are you trying to accomplish?
If the goal is to remove the value in the name/value pair, you might as well just remove the attribute entirely. I'm not aware of any intrinsic value in maintaining an attribute that has no value; in less standards-compliant browsers it may even cause a problem.
In general, the syntax of $(selector).attr(name, value) and $(selector).removeAttr(name) work very well (at least I've never seen it fail.)
If you're trying to use void(0) to keep A HREFs from firing you'd be better off using a "return false" as the click event on those A tags.
The only way to work with custom attributes via jQuery objects is:
obj.get(0).myCustomAttr = 'some value';
That is because jQuery's attr() method will not work with custom attributes (except while applied on a XML-document).
Note also that meouw's answer regarding jQuery overloading functions is not precisely correct, because jQuery checks for the parameters passed to it in such a manner that:
jQuery.funcname(param)
and
jQuery.funcname(param, null)
differ, becacuse null !== undefined. For example:
var params_test = function(a) {
if (a === undefined) {
return 'called with no parameters';
} else {
return 'called with one parameter: ' + a;
}
};
params_test(); // results in 'called with no parameters'
params_test(null); // results in 'called with one parameter: null'
Uhmm, try this:
javascriptElementObject.attr("customAttribute", void(0));
var _void = javascriptElementObject.attr("customAttribute");
alert(_void);

Categories

Resources