main.js 8.28 KB
Newer Older
1 2 3
var cont_experiencia = 0;
let cont_estudios = 0;
let cont_tecnologia = 0;
4 5 6
const experiencias = [];
const estudios = [];
const tecnologias = [];
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

const formValidator = function () {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.querySelectorAll('.needs-validation')
    var expForm = document.querySelector('#agregar-exp')


    // Loop over them and prevent submission
    Array.prototype.slice.call(forms)
        .forEach(function (form) {
            form.addEventListener('submit', function (event) {
                if (!form.checkValidity()) {
                    event.preventDefault()
                    event.stopPropagation()
                }

                form.classList.add('was-validated')
            }, false)
        })
}

function agregarFieldExpierncia(event){
31 32 33 34
    //recoger del form
    const pairs = {};
    const formexp = document.querySelector("[name=experiencia-form]");
    const formData = new FormData(formexp);
35 36
    const reconocimientos = [{},{},{}];
    let pos_rec;
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    let returnFlag = false;

    formData.forEach((value, key)=>{
        if((key === "institucion" || key === "cargo" || key === "fechaDesde")
        && value==="" && returnFlag == false){
            console.log(key, value)
            returnFlag = true;
        }
    });

    if(returnFlag===true){
        alert("Rellene Institucion, Fechas y Cargo como minimo");
        return;
    }

52
    for (const [name, value] of formData){
53 54 55 56 57 58 59 60
        pos_rec = name.split("-");//rec-nombre-index
        if (pos_rec.length > 1) {
            reconocimientos[pos_rec[2]][pos_rec[1]] = value
        }
        else{
            pairs[name] = value
        }
        
61
    }
62
    pairs["reconocimientos"] = reconocimientos.filter(rec => rec.nombre);
63 64 65 66 67 68 69 70 71 72 73 74
    experiencias[cont_experiencia] = pairs;
    formexp.reset();
    //imprimir lista actualizada
    const div = document.querySelector("#experiencias")
    const div1 = document.createElement('div');
    let content='<ul>'
    for (let index = 0; index < experiencias.length; index++) {
        const exp = experiencias[index];
        if(exp==null) continue;
        content += `
        <li id="exp-${index}">        
            ${exp.institucion}
Nelson Ruiz committed
75
            <button type="button" onclick="eliminarExperiencia(event)"> <span class="glyphicon glyphicon-trash"></span> Tras</button>
76 77 78 79 80 81 82 83
        </li>
        
        `
    }
    content += "</ul>" 
    div1.innerHTML = content
    div.innerHTML = '';
    div.appendChild(div1);
84 85
    cont_experiencia++;
}
willgonzz committed
86 87 88 89 90 91 92 93 94 95
/*--------------------------------------------------------------------*/
function agregarFieldTecnologia(){
    //recoger del form
    const pairs = {};
    const formtecn = document.querySelector("[name=tecnologia-form]");
    const formData = new FormData(formtecn);
    for (const [name, value] of formData){
        pairs[name] = value
    }
    tecnologias[cont_tecnologia]={}
96
    tecnologias[cont_tecnologia]["tecnologia"]=pairs["tecnologia-id"]=="-1"?{nombre: pairs["tecnologia-nombre"]}:{id: pairs["tecnologia-id"],nombre:document.querySelector('[name=tecnologia-id] > option[value="'+pairs["tecnologia-id"]+'"]').innerHTML}
willgonzz committed
97 98 99
    tecnologias[cont_tecnologia]["nivel"]=pairs.nivel
    //tecnologias[cont_tecnologia] = pairs;
    formtecn.reset();
100
    document.querySelector("#tecnologia-nombre").classList.add('d-none')
willgonzz committed
101 102 103 104
    //imprimir lista actualizada
    const div = document.querySelector("#tecnologias")
    const div1 = document.createElement('div');
    console.log(tecnologias[0])
105

willgonzz committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    let content1='<ul>'
    for (let index = 0; index < tecnologias.length; index++) {
        const tecn = tecnologias[index];
        if(tecn==null) continue;
        content1 += `
        <li id="tecn-${index}">        
            ${tecn.tecnologia.nombre} 
            <button type="button" onclick="eliminarTecnologia(event)">Eliminar</button>
        </li>
        
        `
    }
    content1 += "</ul>" 
    div1.innerHTML = content1
    div.innerHTML = '';
    div.appendChild(div1);
    cont_tecnologia++;
123
}
124

willgonzz committed
125 126

/*--------------------------------------------------------------------*/
127
function eliminarExperiencia(event) {
128 129 130
    //eliminar del array
    experiencias[event.target.parentElement.id.split("-")[1]]=null
    //eliminar en html
131 132
    event.target.parentElement.remove()
}
willgonzz committed
133 134 135 136 137 138 139 140
/*----------------------------------------------------------------- */
function eliminarTecnologia(event) {
    //eliminar del array
    tecnologias[event.target.parentElement.id.split("-")[1]]=null
    //eliminar en html
    event.target.parentElement.remove()
}
/*----------------------------------------------------------------- */
141 142 143 144 145 146 147 148 149
function serializeJSON (form) {
    // Create a new FormData object
    const formData = new FormData(form);

    // Create an object to hold the name/value pairs
    const pairs = {};

    // Add each name/value pair to the object
    for (const [name, value] of formData) {
150
        pairs[name] = value
151
    }
152 153 154
    pairs["experiencias"] = experiencias.filter(exp => exp)//eliminacion de nulos
    pairs["estudios"] = estudios.filter(est => est)//eliminacion de nulos
    pairs["tecnologias"] = tecnologias.filter(tec => tec)//eliminacion de nulos
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    
    // Return the JSON string
    return JSON.stringify(pairs, null, 2);
}

async function postData(url = '', data = {}) {
    // Default options are marked with *
    const response = await fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
        'Content-Type': 'application/json'
        // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: data // body data type must match "Content-Type" header
    });
    return response; // parses JSON response into native JavaScript objects
}
177
formValidator()
178 179
form = document.querySelector("form");
form.addEventListener("submit",(evt)=>{
180 181 182 183 184
    // if (!form.checkValidity()) {
    //     evt.preventDefault()
    //     evt.stopPropagation()
    // }
    // form.classList.add('was-validated')
185 186
    postData('postulante', serializeJSON(form))
    .then(response => {
187 188
        if(response.status==200 || response.status==302){
            location.replace(response.url);
189 190
        }else{
            console.log(response.text().then(value => console.log(value)))
191
        }
192 193
    });
    evt.preventDefault();
194 195
} );

Joel Florentin committed
196
document.querySelector("#btn-new-tech").addEventListener('click',()=>{document.querySelector("#tecnologia-nombre").classList.remove('d-none')})
197 198 199 200 201 202 203 204 205 206 207


//Metodos para Estudios



function agregarFieldEstudio(){
    //recoger del form
    const pairs = {};
    const formest = document.querySelector("[name=estudio-form");
    const formData = new FormData(formest);
208 209
    const estudioReconocimiento = [{},{},{}];
    let pos_rec;
210
    for (const [name, value] of formData){
211 212 213 214 215 216 217 218
        pos_rec = name.split("-");//rec-nombre-index
        if (pos_rec.length > 1) {
            estudioReconocimiento[pos_rec[2]][pos_rec[1]] = value
        }
        else{
            pairs[name] = value
        }
        
219
    }
220
    pairs["estudioReconocimiento"] = estudioReconocimiento.filter(rec => rec.nombre);
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    estudios[cont_estudios] = pairs;
    formest.reset();
    //imprimir lista actualizada
    const div = document.querySelector("#estudios")
    const div1 = document.createElement('div');
    let content='<ul>'
    
    for (let index = 0; index < estudios.length; index++) {
        const est = estudios[index];
        if(est==null) continue;
        content += `
        <li id="est-${index}">        
            ${est.institucion}
            <button type="button" onclick="eliminarEstudio(event)">Eliminar</button>
        </li>
        
        `
    }
    content += "</ul>" 
    div1.innerHTML = content
    div.innerHTML = '';
    div.appendChild(div1);
    cont_estudios++;

}

function eliminarEstudio(event) {
    //eliminar del array
    estudios[event.target.parentElement.id.split("-")[1]]=null
    //eliminar en html
    event.target.parentElement.remove()
}