Reputation: 105
I want to print any object. I hope you understand, what i want. I am new. Below is my code,
function abhi(x)
{
var abhi = new Object();
abhi.first_name = "abhijit";
abhi.last_name = "Das";
abhi.age = 22;
document.getElementById("name").innerHTML = abhi.x ;
}
</script>
<p id="name"></p>
<input type="submit" name="submit" value="Name" onclick="abhi(age)"/>
</body>
Upvotes: 0
Views: 87
Reputation: 23386
In HTML you need to pass a string:
onclick="abhi('age')"
If age
is a variable containing "age"
, it's OK.
Then you can use it in the script like this:
document.getElementById("name").innerHTML = abhi[x];
You can read more about the bracket notation and objects at MDN.
Upvotes: 3
Reputation: 79022
<script type="text/javascript">
function getAbhi(x) {
var abhi = {
first_name: "abhijit",
last_name: "Das",
age: 22
};
document.getElementById("name").innerHTML = abhi[x];
}
</script>
<p id="name"></p>
<input type="submit" name="submit" value="Name" onclick="getAbhi('age')" />
http://jsfiddle.net/samliew/H7Zs9/7/
Upvotes: 0
Reputation: 367
You have to use this line
document.getElementById("name").innerHTML = abhi[x] ;
Upvotes: 0
Reputation: 97672
You'll have to use square bracket notation to access properties of objects by passing a string.
document.getElementById("name").innerHTML = abhi[x];
...
<input type="submit" name="submit" value="Name" onclick="abhi('age')"/>
Upvotes: 2