Soy un principiante con Javascript/programación y estoy tratando de hacer que el id "demo2" cambie con la variable 5, 10 o 15 elegida en las funciones (disparador por los botones), pero sigue mostrando "0". ¿Que tengo que hacer?
<!DOCTYPE html> <html> <body> <button onclick="alternative1()">5</button> <button onclick="alternative2()">10</button> <button onclick="alternative3()">15</button> <p id="demo"></p> <p id="demo2"></p> <script> var x = 0; var y = 0; function alternative1() {y = x + 5; document.getElementById("demo").innerHTML = "You have chosen " + y; } function alternative2() {y = x + 10; document.getElementById("demo").innerHTML = "You have chosen "+ y; } function alternative3() {y = x + 15; document.getElementById("demo").innerHTML = "You have chosen "+ y; } document.getElementById("demo2").innerHTML = y; </script> </body> </html>No puede acceder a las variables declaradas dentro de una función desde fuera de una función. La variable pertenece solo al ámbito de la función, no al ámbito global.
No necesitas 3 funciones para esto. Puedes hacerlo con 1.
<!DOCTYPE html> <html> <body> <button onclick="alternative(this)">5</button> <button onclick="alternative(this)">10</button> <button onclick="alternative(this)">15</button> <p id="demo"></p> <script> function alternative(obj) { document.getElementById("demo").innerHTML = "You have chosen " + obj.innerHTML; } </script> </body> </html>Feliz aprendizaje
Es normal que haya cero porque en 'y' hay cero y no se realiza ninguna operación en y.
Espero que esta respuesta te ayude a entender lo que has hecho.