使用 JavaScript 验证表单(从 cbx 中选择的有效选项)



HTML - 这是一个简单的 html 表单,我必须用 js 验证,如果有人可以帮助我......

<form>
<label class="ancho">Nombre</label>
<input id="name" class="bloque" type="text" placeholder="Nicolas">
<label class="ancho">Apellido</label>
<input id="surename" class="bloque" type="text" placeholder="Oyarzun">
<label class="ancho">Edad</label>
<input id="age" class="bloque" type="number" placeholder="27" min="1" max="110">
<label class="ancho">Carrera</label>
    <select id="cbxCarrera" class="bloque">
        <option id="op0">-- Seleccione una Carrera --</option>
        <option id="op1">Programacion</option>
    </select>
    <button class="bloque boton" onclick="formulario()">Enviar</button
</form>

JavaScript

<script>
    var nombre = document.getElementById("name");
    var apellido = document.getElementById("surename");
    var edad = document.getElementById("age");
    var carrera = document.getElementById("cbxCarrera");
    var opcion0 = document.getElementById("op0");
    var opcion1 = document.getElementById("op1");
    function formulario() {
        while (nombre != null || apellido != null || edad > 0) {
            if (document.getElementById("cbxCarrera").value != "0") {
                // just checking if displays
                alert("nombre: " + nombre "apellido: " + apellido "edad: " + edad "carrera: "
                    document.getElementById(id).optSelected);
            }
        } else {
            alert("Porfavor ingrese valores validos en los campos anteriores.");
        }
    }
</script>

如何验证在组合框中选择的选项?谢谢!

你可以通过使用 selectedIndex 来获取选定的选项,如下所示

carrera.options[carrera.selectedIndex];

然后随心所欲地使用它,

参考

最新更新