No estoy seguro de lo que estoy haciendo exactamente, pero tengo un código que funciona en este momento. Quiero tener un montón de códigos postales y cuando alguien ingrese su código postal y haga clic en enviar, devolverá un mensaje. En lugar de que el mensaje solo se muestre a medida que escribe. ¡Cualquier ayuda es apreciada!
<!DOCTYPE html> <html> <body> <h1 style="color:black; font-family: arial; font-size: 110%; ">Not sure if we deliver to your area?</h1> <h2 style="color:black; font-family: arial; font-size: 90%; font-weight:40; ">Enter your zip code to find out.</h1> <input type="text" id="zipCode" placeholder="ZIP code" onKeyUp="validateZip()"/> <div id="msg" style="color:black; font-family: arial; font-size: 90%; font-weight:40; margin-top: 10px;"></div> <script> function checkIfAvailable(zip) { let zones = ["55075","55118","55115"] return( zones.indexOf(zip) >= 0 ) } function validateZip() { let zip = document.getElementById("zipCode").value; let msg ="" if(checkIfAvailable(zip)) { msg="We deliver to your area!"; } else { msg="Sorry, we do not deliver to your area."; } document.getElementById("msg").innerHTML = msg; } </script> </body> </html>Su secuencia de comandos funciona como se esperaba aquí, actualmente está ejecutando validateZip cada vez que se presiona una tecla, porque está en el atributo onKeyUp de su elemento de entrada.
Para ejecutar esta función cuando se hace clic en el botón Enviar, ejecute el script en el atributo "onClick" de un botón.
Por ejemplo:
<input type="text" id="zipCode" placeholder="ZIP code" /> <div id="msg" style="color:black; font-family: arial; font-size: 90%; font-weight:40; margin-top: 10px;"></div> <button onclick="validateZip()">Submit</button>De esta manera, solo se ejecuta una vez, no cada vez que presiona una tecla.
Entonces, acabo de agregar un eventListener a un botón
<!DOCTYPE html> <html> <body> <h1 style="color:black; font-family: arial; font-size: 110%; ">Not sure if we deliver to your area?</h1> <h2 style="color:black; font-family: arial; font-size: 90%; font-weight:40; ">Enter your zip code to find out.</h2> <input type="text" id="zipCode" placeholder="ZIP code" /> <button id="sendButton">Send</button> <div id="msg" style="color:black; font-family: arial; font-size: 90%; font-weight:40; margin-top: 10px;"></div> <script> var button = document.getElementById("sendButton"); function checkIfAvailable(zip) { let zones = ["55075", "55118", "55115"] return (zones.indexOf(zip) >= 0); } button.addEventListener("click", function validateZip() { let zip = document.getElementById("zipCode").value; let msg = ""; if (checkIfAvailable(zip)) { msg = "We deliver to your area!"; } else { msg = "Sorry, we do not deliver to your area."; } document.getElementById("msg").innerHTML = msg; }); </script> </body> </html>