0

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>
Rithesh M
1,2871 gold badge12 silver badges23 bronze badges
asked Feb 14, 2013 at 6:58
1
  • Instead of document.getElementById("name").innerHTML = abhi.x ;, use document.getElementById("name").innerHTML = x ; Commented Feb 14, 2013 at 7:01

4 Answers 4

3

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.

answered Feb 14, 2013 at 7:01
Sign up to request clarification or add additional context in comments.

Comments

2

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')"/>
answered Feb 14, 2013 at 7:01

Comments

0

You have to use this line

document.getElementById("name").innerHTML = abhi[x] ;
answered Feb 14, 2013 at 7:07

Comments

0
<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/

answered Feb 14, 2013 at 7:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.