Carl
Carl

Reputation: 5779

Changing contents of button when clicked

For some reason I'm stumped trying to change the contents of a button when clicked. Here is my code:

<!DOCTYPE html>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Exam 2</title>
</head>
<body>
    <div>
<p>
    <button id="button">Start</button>
    </p></div>
    <p id="result"></p>
    <div><p>
        <img src="turret-portal.jpg" height="150" width="100"/>
        </p></div>

    <script>
var button=document.getElementById("button");
button.onclick = function() {
     button.value = "test";
};    
    </script>
    </body>
</html>

I feel like I am fundamentally misunderstanding something.

Thanks for your help

edit:

This also doesn't work:

<!DOCTYPE html>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Exam 2</title>
</head>
<body>
    <div>
<p>
    <button id="button">Start</button>
    </p></div>
    <p id="result"></p>
    <div><p>
        <img src="turret-portal.jpg" id="pic" height="150" width="100"/>
        </p></div>

    <script>
document.getElementById("button").onclick = function() {
     document.getElementById("button").innerText = "test";
};    
    </script>
    </body>
</html>

Upvotes: 0

Views: 2201

Answers (2)

mati
mati

Reputation: 5348

You don't want to change the value attribute. You want to modify the text content.

So you can replace button.value = "test"; with button.innerText = "test";.

Also, you can change the data for the text node that's inside your button element, as stated in this other answer.

Upvotes: 1

MrMadsen
MrMadsen

Reputation: 3012

Change your javascript to this:

var button=document.getElementById("button");
button.onclick = function() {
    button.innerHTML = "test";
};

You would use .value if it was <input type=button/>

Here is working fiddle: https://jsfiddle.net/q0g8c78q/

Upvotes: 1

Related Questions