I have:
if (!myObj.login_id) {
alert("The object for login_id does not exist.");
} else {
alert("The object for login_id DOES exist. The value of the object is: " + myObj.login_id);
}
This is working properly. The object and it's value are defined already. However, I have multiple objects which are named after their ID attr. So, I try doing this (say for example this is a click event:
objtitle = $(this).attr('id'); // this is "login_id"
if (!myObj.objtitle) {
alert("The object for "+objtitle+" does not exist.");
} else {
alert("The object for "+objtitle+" DOES exist. The value of the object is: " + myObj.objtitle);
}
Why does it stop working when I use a variable for the name of the object?
Use square brackets.
myObj[objtitle]
There are two ways of accessing an object's properties: the dot syntax and the square bracket syntax. These are called member operators. So the following two are equivalent:
obj.foo
obj['foo']
The dot syntax (the first one) is a literal name. obj.objtitle therefore attempts to find a property called objtitle. If you have a variable containing the property name you want, you have to use the square bracket syntax.
myObj[objtitle]
Related
I am trying to click on the first radio button and it will assign variables distSelected and weapon some values from the object engDistanceObject. I suspect my HTML might not be written correctly... specifically the input tags.
https://jsfiddle.net/Natronox/sbojaxm4/#&togetherjs=zb80KxkQzm
var engDistanceObject = {
short: ["100m-300m","416 Assault Rifle"],
long: ["300m-1000m","M110 DMR"]
};
var distSelected;
var weapon;
function distanceClick(item){
distSelected = engDistanceObject.item[0];
weapon = engDistanceObject.item[1];
console.log(distSelected,weapon);
};
Use your short and long properties instead of item. You don't have an item property name in your object.
.short[0]
.short[1]
To access dynamic properties, you can't use the . syntax. It ignores variables that might have the same name as the property you're trying to access, and instead will try to access the non-existent item property.
Instead, use the bracket syntax [], which allow a string to be used to access dynamic properties. This means that you need to pass a string as a parameter to your function.
Your HTML event handlers will need quotes around the parameters:
onclick="distanceClick('long')"
And then use the bracket syntax in your JS:
function distanceClick(item){
distSelected = engDistanceObject[item][0];
weapon = engDistanceObject[item][1];
console.log(distSelected, weapon);
}
I'm trying to sort out if this is plausible but have gotten syntax errors at best. So I am wondering if it is at all possible.
What I have is an object (example only)
var myObj = {
something1_max:50,
something1_enabled:false,
something1_locked:true,
something2_max:100,
something2_enabled:false,
something2_locked:true,
something3_max:10,
something3_enabled:true,
something3_locked:true
}
and what I want to do through a function is do something like again for example to sum things up..
function displayDetails(theScope, obj)
{
console.log(obj.[theScope]_max);
}
(function(){displayDetails('something3', myObj);})()
so when displayDetails() is called whatever the scope I can see in this example the max for that scope. In the console log for the example I would hope to see 10
Properties of JavaScript objects can always be accessed as a string using the bracket syntax, ie object['property']. This, of course, means you can build that string dynamically:
console.log(obj[theScope + '_max']);
Put the property name string in brackets.
console.log(obj[theScope + '_max']);
I am trying to run some JavaScript, but it is not working.
I have an object with two properties that are also objects.
var people = {
me: {
name: "Hello"
},
molly: {
name: "Molly"
}
};
And I am trying to make a function that uses a for/in statement and an if statement to list the properties of people.
var search = function (x) {
for (var a in people) {
if (people.a.name === x) {
return people.a;
}
}
};
So the function loops through the properties of people and assigns them to the variable a. Therefore people.a will be equal to a property of people. Then the function returns the property (people.a).
So if I type in me as parameter x, will the function should return the properties for the me object? I put this code in jsLint and jsHint and it passed, but I decided to remove the corrections because they were useless.
I then want to print the object properties in the browser:
var print = search("me");
document.getElementById("p").innerHTML(print);
I have this linked to an html document, with a tag id "p". I have tested javascript in the html document already, so I know that the javascript document is linked properly.
But the code will not work. Does anyone have any suggestions?
I have it working now thanks to the answers. But I thought that it would only print "Hello" to the screen, not { name: "Hello"}.
You need to use people[a], not people.a. The former looks for a property with the name of the value stored in a; the latter looks for a property literally named "a", which of course doesn't exist.
for (var a in people) {
if (people[a].name === x) {
return people[a];
}
}
Fiddle here.
Also, I think you meant search("Hello"), right? If not, then it would just be var search = function(x) { return people[x]; }.
people.a.name
you need to use the bracket operator if you want to access an item by name. Using people.a is literally searching for a member named 'a' instead of a member with the same name as the value of a.
Try:
people[a].name
instead.
4 errors in your code:
replace people.a with people[a]
replace innerHTML() with innerHTML
set HTML like this: document.getElementById("p").innerHTML = print.name;
As in a previous answer, search by name
Code: http://jsfiddle.net/nabil_kadimi/vVSPG/
function doIt()
{
var person={firstname:"John", lastname:"Smith", age:"25"};
var x;
var txt="";
for (x in person)
{
txt=txt+person[x] +"<br>";
}
document.getElementById("showtext").innerHTML=txt;
}
My question is: Why when I replace
txt=txt+person[x]+"<br>";
with:
txt=txt+person.x+"<br>";
the value of person.x is returned as undefined?
In the first iteration of the loop, x should be 'firstname'. So person.x should be equal to person.firstname, and thus return the value John. I would love to understand why it returns 'undefined' instead.
In the first case you're using 'bracket notation', where the value of the variable x is used to determine the property name.
In the second case you're using 'dot notation', where the property looked for is literally called x.
The Answer is:
Since x ist not the property name and the object doesnt have a property with the name/key x.
person.x
is undefined.
This would be equivalent to
person["x"] (the subtle difference lies in the double quotes)
what is also undefined.
For it to work with the dot-notation, you would have to write :
eval("person." + x); // but this is evil
// Tested on win7 with chrome 45+
so expression eval("person." + x) would expand in the first run to eval("person.firstname" ) which returns "John"
...
What I don't recommend, because eval can introduce may security issues.
Update 1
Disclaimer:
With this answer i only answered the initial question, and tried to explain the problem. With "// but this is evil " i am suggesting not to use this approche.
When you write person[x], it means "look up the value of x, and then find that element in person". When you write person.x it means "look up the value of x inside of person".
person doesn't have an x element, so you're getting undefined. You really do just want person[x].
x will be a string. eg "person" so you have to use [] brackets
You can't use dot notation with a variable key. It will look up the property "x" which is undefined. person[x] is the right way.
Javascript will allow you to access an object's property using a variable if you use the square brackets syntax. Thus, person[x] will do what you are trying to do as long as x contains a string representing the property name. The syntax construction person.x is equivalent to person["x"].
This is surely a JS beginner question.
My issue is I want to use the value of the variable type to access the relevant checkbox; however it is treating the variable as a string. I have tried it to two ways.
function toggleGroup(type) {
if (document.getElementById(type).checked == true){
alert("foo");
}
}
or
function toggleGroup(type) {
if (document.nav.type.checked == true){
alert("foo");
}
}
We have no way of knowing how type should be treated - you haven't show us how the function is being called (in particular, we don't know what you are passing as its argument).
If it is a string (matching the id of an element), than document.getElementById(type).checked should work (although == true is redundant).
document.nav.type.checked should not work, because dot-notation property names are not interpolated. You have to use square bracket notation for that: document.forms.nav.elements[type].checked. This will match on name or id - if you have multiple elements with the same name, then document.forms.nav.elements[type] will be an object you can treat as an array (and won't have a checked property).
you can as well compare with "true"