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>
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.

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')"/>

Comments

0

You have to use this line

document.getElementById("name").innerHTML = abhi[x] ;

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/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.