Run javascript verification function within the registry creation function

0

I have a javascript function to create a record called createSancion , it verifies the fields and then shows a message to confirm the saved, if it is accepted it becomes a form.submit

It happens that you add another script to count the data of a checkbox at the end of the record, called verify . and I've tried to set it up to count and then save, but I could not.

I would like that when you give the save button you run the function of creating the record but before showing "you want to save the data" I will verify the checbox, and once verified it says "you want to save the data?"

Try doing it by entering the check function within the creation, but when it verifies after executing it does nothing else.

Also try to place both function calls on the button, but just run the first one you have.

Here I leave the codes:

createSancion ():

function CrearSancion()
{
    var obj1 = window.document.getElementById("cedula");
    var obj2 = window.document.getElementById("cedula1");
    var obj3 = window.document.getElementById("cedula2");   
    var obj4 = window.document.getElementById("narticulo");
    var obj5 = window.document.getElementById("naparte");   
    var obj7 = window.document.getElementById("unidad");
    var obj8 = window.document.getElementById("unidad_uuss");
    var obj9 = window.document.getElementById("estados");
    var obj10 = window.document.getElementById("docanexos");        
    var obj11 = window.document.getElementById("fecha_ultimo");     
    var obj12 = window.document.getElementById("cargo");        
    var obj13 = window.document.getElementById("xdes_sancion");     
    var obj14 = window.document.getElementById("fecha_inicio");
    var obj15 = window.document.getElementById("aclaratoria");
    var obj16 = window.document.getElementById("nombrecompleto1");
    var obj17 = window.document.getElementById("nombrecompleto2");
    var obj18 = window.document.getElementById("nombrecompleto3");  


    if(obj1.value == "")
    {
        alert ("Debe agregar el numero de cedula del sancionado");      
    }
    else if((obj16.value == ""))
    {
        alert ("Debe ingresar el nombre del sancionado");       
    }
    else if((obj17.value == ""))
    {
        alert ("Debe ingresar el nombre del sancionado");       
    }
    else if((obj18.value == ""))
    {
        alert ("Debe ingresar el nombre del sancionado");       
    }
    else if((obj2.value == ""))
    {
        alert ("Debe agregar el numero de cedula del que sanciona");        
    }

    else if((obj4.value == "0"))
    {
        alert ("Debe agregar el articulo");     
    }
    else if((obj5.value == "0"))
    {
        alert ("Debe agregar el aparte del articulo");      
    }   


    else if((obj9.value == "0"))
    {
        alert ("Debe seleccionar el lugar donde se realiza la sancion");        
    }

    else if((obj10.value == "0"))
    {
        alert ("Debe seleccionar el tipo de documento anexado a la sancion");       
    }
    else if((obj11.value == ""))
    {
        alert ("Debe agregar la fecha del ultimo ascenso");     
    }
    else if((obj12.value == ""))
    {
        alert ("Debe agregar el cargo");        
    }
    else if((obj13.value == "0"))
    {
        alert ("Debe agregar el tipo de sancion");      
    }
    else if((obj14.value == ""))
    {
        alert ("Debe agregar la fecha de inicio de la sancion");        
    }
    else if((obj15.value == ""))
    {
        alert ("Debe agregar la aclaratoria de la sancion");        
    }

    else
    {
            if(confirm('Esta seguro que desea guardar los datos'))
        {
            var obj1 = window.document.getElementById('accion');
            obj1.value = 'I';
            form1.submit(); 
    }
    }
}

verify ():

    function verificar(){
alert("Verificando sus datos Selección de Circunstancias Atenuantes");

var cb = [];
var atenuantes="atenuantes[]";
var n1=0,cuales="";
cb = document.getElementsByName(atenuantes);
    for (var i = 0; i < cb.length; i++){
    var e = parseInt(i);
        if(cb[i].checked == true){
        cuales += cb[i].value + ' ';
        n1++;
        }
    } // fin loop
    if(n1 == 0){
    var mensaje1 = 'No hubo selección de atenuantes';
    }else{
    var mensaje1 = 'Se marcaron el/las opción(es) de valor(es): ' + cuales
    }
alert('El total de opciones marcadas es: ' + n1);
alert(mensaje1);

alert("Verificando sus datos Selección de Circunstancias Agravantes");
var cb2 = [];
var agravantes="agravantes[]";
var n2=0,cuales2="";
cb2 = document.getElementsByName(agravantes);
    for (var i = 0; i < cb2.length; i++){
    var e = parseInt(i);
        if(cb2[i].checked == true){
        cuales2 += cb2[i].value + ' ';
        n2++;
        }
    } // fin loop
    if(n2 == 0){
    var mensaje2 = 'No hubo selección de agravantes';
    }else{
    var mensaje2 = 'Se marcaron el/las opción(es) de valor(es): ' + cuales2
    }
alert('El total de opciones marcadas es: ' + n2);
alert(mensaje2);
document.getElementById('boxes').reset();
}

html button:

<input type="button" name="crear" onClick="CrearSancion();" value="Aceptar" />

I put it at the end, since it shows 4 messages and it would be cumbersome to show the 4 messages every time you lack a value

    
asked by Victor Alvarado 10.02.2017 в 16:41
source

3 answers

1

You just have to send one function to another. I recommend doing the validations in javascript using "return;" to finish with the execution of the method and return to the form to update the information, this way you avoid using the else all the time. In any case, your function as you have it should look something like this:

function CrearSancion()
{
    var obj1 = window.document.getElementById("cedula");
    var obj2 = window.document.getElementById("cedula1");
    var obj3 = window.document.getElementById("cedula2");   
    var obj4 = window.document.getElementById("narticulo");
    var obj5 = window.document.getElementById("naparte");   
    var obj7 = window.document.getElementById("unidad");
    var obj8 = window.document.getElementById("unidad_uuss");
    var obj9 = window.document.getElementById("estados");
    var obj10 = window.document.getElementById("docanexos");        
    var obj11 = window.document.getElementById("fecha_ultimo");     
    var obj12 = window.document.getElementById("cargo");        
    var obj13 = window.document.getElementById("xdes_sancion");     
    var obj14 = window.document.getElementById("fecha_inicio");
    var obj15 = window.document.getElementById("aclaratoria");
    var obj16 = window.document.getElementById("nombrecompleto1");
    var obj17 = window.document.getElementById("nombrecompleto2");
    var obj18 = window.document.getElementById("nombrecompleto3");  


    if(obj1.value == "")
    {
        alert ("Debe agregar el numero de cedula del sancionado");      
    }
    else if((obj16.value == ""))
    {
        alert ("Debe ingresar el nombre del sancionado");       
    }
    else if((obj17.value == ""))
    {
        alert ("Debe ingresar el nombre del sancionado");       
    }
    else if((obj18.value == ""))
    {
        alert ("Debe ingresar el nombre del sancionado");       
    }
    else if((obj2.value == ""))
    {
        alert ("Debe agregar el numero de cedula del que sanciona");        
    }

    else if((obj4.value == "0"))
    {
        alert ("Debe agregar el articulo");     
    }
    else if((obj5.value == "0"))
    {
        alert ("Debe agregar el aparte del articulo");      
    }   


    else if((obj9.value == "0"))
    {
        alert ("Debe seleccionar el lugar donde se realiza la sancion");        
    }

    else if((obj10.value == "0"))
    {
        alert ("Debe seleccionar el tipo de documento anexado a la sancion");       
    }
    else if((obj11.value == ""))
    {
        alert ("Debe agregar la fecha del ultimo ascenso");     
    }
    else if((obj12.value == ""))
    {
        alert ("Debe agregar el cargo");        
    }
    else if((obj13.value == "0"))
    {
        alert ("Debe agregar el tipo de sancion");      
    }
    else if((obj14.value == ""))
    {
        alert ("Debe agregar la fecha de inicio de la sancion");        
    }
    else if((obj15.value == ""))
    {
        alert ("Debe agregar la aclaratoria de la sancion");        
    }



      else
        {
    //Una vez que terminaste de verificar que la información no esté vacía puedes llamar al método que verifica lo de los checkbox y hacer que regrese un true/false y dependiendo de eso hacer la pregunta del confirm.

                if(verificar()){
                    if(confirm('Esta seguro que desea guardar los datos')){
                    var obj1 = window.document.getElementById('accion');
                    obj1.value = 'I';
                    form1.submit(); 
            } 
        }
        }
    }

And the verify () function would look like this:

function verificar(){
alert("Verificando sus datos Selección de Circunstancias Atenuantes");

var cb = [];
var atenuantes="atenuantes[]";
var n1=0,cuales="";
cb = document.getElementsByName(atenuantes);
    for (var i = 0; i < cb.length; i++){
    var e = parseInt(i);
        if(cb[i].checked == true){
        cuales += cb[i].value + ' ';
        n1++;
        }
    } // fin loop
    if(n1 == 0){
    var mensaje1 = 'No hubo selección de atenuantes';
    return false; //Para que no dé submit
    }else{
    var mensaje1 = 'Se marcaron el/las opción(es) de valor(es): ' + cuales
    }
//alert('El total de opciones marcadas es: ' + n1);
//alert(mensaje1); Si realmente necesitas estos alerts se los descomentas

alert("Verificando sus datos Selección de Circunstancias Agravantes");
var cb2 = [];
var agravantes="agravantes[]";
var n2=0,cuales2="";
cb2 = document.getElementsByName(agravantes);
    for (var i = 0; i < cb2.length; i++){
    var e = parseInt(i);
        if(cb2[i].checked == true){
        cuales2 += cb2[i].value + ' ';
        n2++;
        }
    } // fin loop
    if(n2 == 0){
    var mensaje2 = 'No hubo selección de agravantes';
    return false; //Para que no dé submit
    }else{
    var mensaje2 = 'Se marcaron el/las opción(es) de valor(es): ' + cuales2


       }
    alert('El total de opciones marcadas es: ' + n2);
    alert(mensaje2);
//No entiendo bien tus validaciones, pero si necesitas que esté seleccionado algún checkbox para poder hacer submit entonces validas
if(n1 > 0 && n2 > 0){
return true; //Verifica que se haya seleccionado al menos un checkbox para cada caso
} else { //Si no se seleccionó al menos uno checkboc para ambos casos entonces no dará submit
return false;
}
    //document.getElementById('boxes').reset(); Sitúa esta línea antes de algún return dependiendo lo que quieras que haga.
    }

Try it and tell us. Your code is not the most apt to say, but it should work.

    
answered by 10.02.2017 / 17:35
source
1

I think you should organize your code. I see that you are using confirm after to validate the form, this you should do before.

I would organize your code in this way:

  

CreateSancion function:

function CrearSancion() {

    var errores = "";

    if (confirm('Esta seguro que desea guardar los datos')) {
        errores = verificar();

        // Si tiene errores, mostrarlos.
        if (errores.trim() != "") {
            alert('Se han encontrado estos errores:\n' + errores);
        }
        else {
            var obj1 = window.document.getElementById('accion');
            obj1.value = 'I';
            form1.submit(); 
        }
    }
}
  

Check function:

funcion verificar() {

    var validado = "";

    // Haz todas tus validaciones aquí.
    // Ejemplo:

    var obj1 = window.document.getElementById("cedula");
    if (obj1.value == "") {
        validado += "- Debe agregar el numero de cedula del sancionado.\n";
    }
    // ...

    return validado;
}

Also, do not place alerts when you reach each step of the verification since the user must accept each alert or the user can select the option:

  

Prevent this page from creating additional dialog boxes.

    
answered by 10.02.2017 в 17:44
0
  • If two javascript functions can be placed in an onclick event
  • I do not understand very well if it is that the verify function is not executed or is that when it executes nothing happens, at least you get the alerts that are inside the function?
  • answered by 10.02.2017 в 17:32