Escribí un código javascript en un archivo HTML usando una etiqueta de secuencia de comandos, donde quiero saber si mi entrada es mayor o menor que 10 o igual a 10 o cualquier entrada en blanco. Utilizo el método if-else para resolver este problema, pero mi última condición if, que es "Su entrada está en blanco", no se genera de ninguna manera.
//f1 function will run when some hit the submit button function f1() { //here we are taking the value of the input field using id "myinput" in the variable called myinputvar var myinputvar = document.getElementById("myinput").value; if (myinputvar > 10) { document.getElementById("txt").innerHTML = "Your input number is greater than 10"; } else if (myinputvar < 10) { document.getElementById("txt").innerHTML = "Your input number is less than 10"; } else if (myinputvar = 10) { document.getElementById("txt").innerHTML = "Your input number is 10"; } else if (myinputvar = " ") { document.getElementById("txt").innerHTML = "Your input is blank"; } } <!-- this is the input tag to take inputs from user --> Enter a integer number between 0 to anynumber = <input type="text" id="myinput"><br><br> <!-- this is the button to submit the value --> <button onclick="f1()">submit</button> <!-- this is the heading tag to print the output --> <h1 id="txt"></h1>Una forma general de verificar solo la entrada de espacios en blanco usa el patrón regex ^\s*$ . Código de muestra:
if (/^\s*$/.test(inputvar)) { document.getElementById("txt").innerHTML = "Your input is blank"; }Envuelva en un formulario y hágalo requerido
También echar a número
document.getElementById("myForm").addEventListener("submit", function(e) { e.preventDefault(); // stop submission //here we are taking the value of the input field using id "myinput" in the variable called myinputvar var myinputvar = +document.getElementById("myinput").value; // make it a number if (myinputvar > 10) { document.getElementById("txt").innerHTML = "Your input number is greater than 10"; } else if (myinputvar < 10) { document.getElementById("txt").innerHTML = "Your input number is less than 10"; } else if (myinputvar = 10) { document.getElementById("txt").innerHTML = "Your input number is 10"; } else if (myinputvar = " ") { document.getElementById("txt").innerHTML = "Your input is blank"; } }) <form id="myForm"> Enter a integer number between 0 to anynumber = <input type="text" required id="myinput"><br><br> <button>submit</button> </form> <h1 id="txt"></h1>presta atención a no usar el atajo:
if (inputvar) { // this won't catch "0"! }pero cuanto mas adecuado
if (inputvar === "") { // is empty }y, por supuesto, primero debe verificar esta condición, si desea manejar números como entrada.