How to change the value of a button once clicked?

1

Good morning, I'm just starting with javascript and it's costing me a little ... What I want to do is that when I click on the button it changes its value, but I do not understand the error:

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">

    <title>Hola mundo</title>
    <script src="holamundo_ext.js"></script>
</head>
<body>
    <input type="button" value="Hola" id="boton" onclick="cambiarboton()">
</body>
</html>

function cambiarboton(){
    var i=document.getElementById("boton").innerHTML("Mundo");

}
window.onload=cambiarboton();

On the console it says:

  

TypeError: document.getElementById (...) is null   TypeError: document.getElementById (...). InnerHTML is not a function

Thank you in advance!

    
asked by Ale 23.11.2017 в 13:18
source

2 answers

6

innerHTML is not a function, but a property so you have to assign it. innerHTML assigns a string or html object to the selected element but a button does not accept html. What you are looking for is to change the value (value), not the HTML:

function cambiarboton(){
    var i=document.getElementById("boton").value = "Mundo";

}
window.onload=cambiarboton();
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">

    <title>Hola mundo</title>
    <script src="holamundo_ext.js"></script>
</head>
<body>
    <input type="button" value="Hola" id="boton" onclick="cambiarboton()">
</body>
</html>

Following your example and this response, the value of the buton is changed at the time of the page load and sure what you want is for the value to change when the button is clicked. Remove the declaration to execute a function when the page loads:

function cambiarboton(){
    var i=document.getElementById("boton").value = "Mundo";

}

// no se necesesita ya que se cambiara cuando se haga clic
//window.onload=cambiarboton();
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">

    <title>Hola mundo</title>
    <script src="holamundo_ext.js"></script>
</head>
<body>
    <input type="button" value="Hola" id="boton" onclick="cambiarboton()">
</body>
</html>
    
answered by 23.11.2017 / 13:22
source
1

To change the content of an HTML element from JavaScript, use the property .innerHTML = "";

In other words, your function cambiarBoton() should be as follows.

function cambiarboton(){
    var i=document.getElementById("boton").innerHTML = "Mundo";

}

In the last line of your code you set the following listen ...

window.onload=cambiarboton();

This means that when all the components of the window have loaded , the function cambiarBoton()

will be executed

But you're also calling the same function every time you press the button.

onclick="cambiarboton()"

If you're looking to change the value by pressing the button, you should leave the latter and delete the listener to the event onload of the window.

    
answered by 23.11.2017 в 13:24