Este bloque de código en mi documento HTML sirve como una función para realizar un cálculo. Solicita al usuario que ingrese la cantidad de habitaciones y el total de pies cuadrados, luego multiplica los pies cuadrados por 5 para obtener la estimación. Estoy tratando de descubrir cómo agregar una declaración if para que sirva como un mensaje de error si un usuario ingresa un número negativo. A continuación se muestra la función copiada del código. ¿Lo agregaría directamente en la función, antes o después? Lo que básicamente quiero decir es,
if (var a && b <= 0) { print "Invalid entry. Please reload the page and enter a positive number." }¿Cómo haría para hacer esto en JavaScript? Además, ¿hay una mejor manera de preguntarle al usuario que usando < p> < /p>?
<div class="container-fluid"> <p>Please enter the number of rooms affected, and the total square foot. </p> <input type="text" name="numRooms" id="numRooms"> <br> <input type="text" name="roomSize" id="roomSize"><br> <button type="button" onclick="submit1()">submit</button><br> <p id="result"></p> </div> <script> function submit1(){ var a = document.getElementById("numRooms").value; var b = document.getElementById("roomSize").value; var c = parseInt(b) * 5; document.getElementById("result").innerHTML="Your estimate is : $" + c; } </script>Puede verificar los valores por adelantado y salir antes, si ocurre un error.
function submit1() { var a = +document.getElementById("numRooms").value; // get a number with + var b = +document.getElementById("roomSize").value; var c = parseInt(b) * 5; if (isNaN(a) || a <= 0 || isNaN(b) || b <= 0) { // check if number or smaller/eq than zero document.getElementById("result").innerHTML = '<span style="color: #b00;">Please insert only positive numbers.</span>'; return; } document.getElementById("result").innerHTML = 'Your estimate is : $ ' + c; } <div class="container-fluid"> <p>Please enter the number of rooms affected, and the total square foot. </p> <input type="text" name="numRooms" id="numRooms"> Rooms<br> <input type="text" name="roomSize" id="roomSize"> Size [sq ft]<br> <button type="button" onclick="submit1()">submit</button><br> <p id="result"></p> </div>