Stormzy
Stormzy

Reputation: 3

How to change property value in JavaScript using built in function?

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>

Upvotes: 0

Views: 216

Answers (4)

Katana314
Katana314

Reputation: 8620

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.

Upvotes: 0

Simon H
Simon H

Reputation: 21027

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;
}

Upvotes: 0

fos.alex
fos.alex

Reputation: 5637

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.

Upvotes: 1

John Boker
John Boker

Reputation: 83729

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>

Upvotes: 3

Related Questions