0

I am trying to simply change the value of someones age which is a property value inside an object i have by clicking a button. I thought this seemed like it should work??

<p id="demo"></p>

<button onclick="incrementAge()">Click me</button>

<script>
var person = {
    name:"Rich",
    age:25, 
    eyeColor:"blue"
};
document.getElementById("demo").innerHTML = person.name + " " + person.age;


function incrementAge(){
    return person.age += 1
}
</script>
3
  • 1
    Sooo? It does work and change the property. Why do you think it doesn't? Commented Oct 21, 2015 at 19:44
  • What are you returning a value to? Commented Oct 21, 2015 at 19:45
  • Of course, you may want to re-render the person into #demo after mutating it. Commented Oct 21, 2015 at 19:45

4 Answers 4

3

You will also need to reset the content of your element on the page:

<p id="demo"></p>

<button onclick="incrementAge()">Click me</button>

<script>
var person = {
    name:"Rich",
    age:25, 
    eyeColor:"blue"
};



function incrementAge(){
    person.age += 1;
    document.getElementById("demo").innerHTML = person.name + " " + person.age;
}
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is the document.getElementById("demo").innerHTML is not binded to the HTML view.

The value is changing but you are not displaying it.

Comments

0

I guess you want the new age to show. If so, you will need to update the innerHTML with that

function incrementAge(){
    person.age += 1;
    document.getElementById("demo").innerHTML = person.name + " " + person.age;
}

Comments

0

I think your code is actually working as you describe, but the effect is different from what you expect.

document.getElementById("demo").innerHTML = person.name + " " + person.age;

^ This is not a transient expression of constant state. There is nothing in your code to say "Always let this be the case."; it will make that change once and not again. What you should be doing is putting this in a refreshNameAge() function, and calling it after any function that might change a person's name and age. Alternatively, you could use Object.defineProperty to tie it into a property getter/setter, although that would end up being more complicated.

Comments

Your Answer

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.