redirect with javascript according to form field

2

I have a form that receives a string and sends it to a java servlet. I'm trying to add a javascript code that allows, if the user enters "000", redirects to the login page. I do this by placing an eventlist onsubmit in the form, but the function is never executed. Here's my page:

I have this inside the header of my page:

        <script type="text/javascript">
            function enviar(){
                valor = document.getElementById("codigo").value;
                if(valor==="000"){
                    location.href="login.jsp";
                }else{
                    return true;
                }

            }

        </script>

And this is the form:

<FORM id="codSeguimiento" onsubmit="enviar();" action="consultaServlet" method="POST">
                <p>Seguimiento de tramites</p>
                <input id="codigo" name="codigo" type=text maxlength="10"><br>
                <input id="boton" name="enviar" type="submit" value="Consultar">        
</FORM>

I have tried commenting the code of the function, and simply placing an alert ("text"); And this never runs. From what I gather the function is never executed.

Any idea what I'm doing wrong? I do not have much idea of the subject

    
asked by Facundo Curti 03.11.2016 в 03:03
source

1 answer

2

The JS enviar function is not executed because within the form there is a input with name enviar . You just have to change the name of the function, example:

function enviarTramite(evt) {
    valor = document.getElementById("codigo").value;
    if (valor === "000") {
        location.href = "login.jsp";
        evt.preventDefault(); // Evitamos el submit en nuevos navegadores
        return false; // Evitamos el submit viejos navegadores
    } else {
        return true;
    }
}

<form id="codSeguimiento" onsubmit="enviarTramite(event);" action="consultaServlet" method="POST">
    <p>Seguimiento de tramites</p>
    <input id="codigo" name="codigo" type=text maxlength="10">
    <br>
    <input id="boton" name="enviar" type="submit" value="Consultar">
</form>

Note : enviarTramite has 2 extra lines to prevent the form from being sent at the same time the redirect is made.

Demo: link

    
answered by 03.11.2016 / 03:40
source