Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't change button text in HTML and JavaScript

I'm trying to change the text of a button using this code, but I'm not getting any reaction. This should be good, looking at everything I've read through - but it doesn't change the text. What am I doing wrong here?

<!DOCTYPE html>
<html>
<head>
    <script>
        function changeText() {
            document.getElementById('myButton').value = "New value";
        }
    </script>
</head>
<body>
    <button id="myButton" onclick="changeText()">Change my text!</button>
</body>
</html>
like image 265
Erik Avatar asked Dec 19 '22 23:12

Erik


2 Answers

You need to set the 'innerHTML' property instead:

function changeText() {
    document.getElementById('myButton').innerHTML= "New value";
}

You can specify a value on the button but it's not used very often. In your case you want to the text of the button to change. So innnerHTML is your friend. See this page for more details.

Also note that you could use 'innerText' in IE as well but it is not supported in Firefox (and probably not in some other as well). 'textContent' can also be an option but that one is not supported in older browsers (before 2011). So innerHTML is the safest option.

like image 133
Bas Slagter Avatar answered Jan 03 '23 09:01

Bas Slagter


Buttons can have a value but what is displayed is the HTML inside of the button, which is what you want to change. Better use innerHTML:

function changeText() {
    document.getElementById('myButton').innerHTML = "New value";
}
like image 43
Roboroads Avatar answered Jan 03 '23 10:01

Roboroads