Estoy tratando de obtener la entrada del usuario del cuadro de texto y luego hacer clic en el botón al lado para calcular el área de un círculo. El problema es que la alerta siempre imprime NaN.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>HTML 5 Boilerplate</title> <link rel="stylesheet" href="./css/style.css"> <script> const PI = 3.14159; function getAreaOfCircle(rad) { let area = PI * Math.pow(rad, 2); alert(area); } </script> </head> <body> <input type="text" placeholder="Type something..." id="myInput"> <input type="button" onclick="getAreaOfCircle();" value="Calculate Area of a Circle"> </body> </html>Tienes que pasar el valor de entrada en tu función. Como su código para pasarlo a su función como argumento/parámetro. Entonces puedes codificarlo así:
<input type="button" onclick="getAreaOfCircle(document.getElementById('myInput').value);" value="Calculate Area of a Circle">Debe obtener el texto de entrada real y convertir su valor en un número flotante:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>HTML 5 Boilerplate</title> <link rel="stylesheet" href="./css/style.css"> <script> const PI = 3.14159; function getAreaOfCircle() { //Get the radius from the input field let rad = document.getElementById("myInput").value; //Check if the input is not empty, if it is set rad to 0 rad = rad !== "" ? parseFloat(rad) : 0; let area = PI * Math.pow(rad, 2); alert(area.toFixed(2)); } </script> </head> <body> <input type="text" placeholder="Enter the circle radius" id="myInput"> <input type="button" onclick="getAreaOfCircle();" value="Calculate Area of a Circle"> </body> </html>No está pasando rad en la función getAreaOfCircle
Entonces puede obtener valor dentro de la función getAreaOfCircle como:
const rad = document.querySelector("#myInput").value; <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>HTML 5 Boilerplate</title> <link rel="stylesheet" href="./css/style.css"> <script> const PI = 3.14159; function getAreaOfCircle() { const rad = document.querySelector("#myInput").value; let area = PI * Math.pow(rad, 2); alert(area); } </script> </head> <body> <input type="text" placeholder="Type something..." id="myInput"> <input type="button" onclick="getAreaOfCircle();" value="Calculate Area of a Circle"> </body> </html>