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>
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.
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With