source: consulta_publica/static/js/funciones.js @ a401f70

constituyenteestudiantesgeneralplan_patriasala
Last change on this file since a401f70 was 0b2127c, checked in by rudmanmrrod <rudman22@…>, 7 años ago

Agregados campos extra para el perfil de usuario

  • Propiedad mode establecida a 100644
File size: 30.1 KB
Línea 
1/**
2 * Función para agregar preguntas en la consulta
3 * @param element Recibe nombre de elemento a agregar
4**/
5function agregar_preguntas(element) {
6    $('#agregar_preguntas').append($(element).html());
7}
8
9/**
10 * Función para eliminar preguntas agregadas dinámicamente
11 * @param element Recibe el elemento a partir del cual se eliminará la fila
12**/
13function eliminar_preguntas(element) {
14    $(element).parent().parent().parent().remove();
15}
16
17/**
18 * Función para validar las preguntas agregadas dinámicamente
19 * @param event Recibe el evento click
20**/
21function validar_preguntas(event) {
22    var longitud = $('#agregar_preguntas').find('.row');
23    if(longitud.length>0)
24    {
25        var vacio = false;
26        $.each(longitud.find('input'),function(key,value){
27            if ($(value).val().trim()=='') {
28                vacio = true;
29            }
30        });
31        $.each(longitud.find('select'),function(key,value){
32            if ($(value).val().trim()=='') {
33                vacio = true;
34            }
35        });
36        if (vacio) {
37            event.preventDefault();
38            bootbox.dialog({
39                message: "Debe llenar todas las preguntas que agregó",
40                title: "<b class='text-danger'>Error</b>",
41                buttons: {
42                    success: {
43                        label: "Cerrar",
44                        className: "btn-danger",
45                        callback: function() {}
46                    }
47                }
48            });
49        }
50    }
51}
52
53/**
54 * Función para cargar preguntas luego de un error en el formulario
55**/
56function cargar_preguntas() {
57    $.each(opciones,function(){
58        $('#agregar_preguntas').append($('#preguntas').html());   
59    });
60    $.each($('#agregar_preguntas #id_texto_pregunta_modal'),function(key,value){
61        $(value).val(opciones[key]['texto_pregunta']);
62    });
63    $.each($('#agregar_preguntas #id_tipo_pregunta_modal'),function(key,value){
64        $(value).val(opciones[key]['tipo_pregunta']).change();
65    });
66}
67
68/**
69 * Función para agregar opciones si la pregunta lo requiere
70 * @param element Recibe el elemento de la consulta
71**/
72function add_option(element) {
73    var option = $(element).parent().parent().parent().find('#for_options');
74    $(option).append($('#agregar_opciones').html());
75}
76
77/**
78 * Función para agregar opciones si la pregunta lo requiere
79 * @param element Recibe el id de la consulta
80**/
81function remove_option(element) {
82    $(element).parent().parent().parent().remove();
83}
84
85/**
86 * Función para mostrar las preguntas de una consulta
87 * @param id Recibe el id de la consulta
88**/
89function ver_preguntas(id) {
90    $.ajax({
91        type: 'GET',
92        url: "/administrador/consulta/ajax/pregunta-list/"+id,
93        success: function(response) {
94            if (response.success) {
95                var preguntas = response.preguntas;
96                var token = $('input').val();
97                var html = '<form action="" role="form" method="post" id="question_form">';
98                html += '<input type="hidden" name="csrfmiddlewaretoken" value="'+token+'">';
99                $.each(preguntas,function(key,value){
100                    html += "<h4>Pregunta #"+parseInt(key+1)+"</h4>";
101                    html+= $('#preguntas').html();
102                    html += "<hr>";
103                });
104                html += "</form>";
105                bootbox.dialog({
106                    message: html,
107                    title: "Preguntas",
108                    buttons: {
109                        success: {
110                            label: "Guardar",
111                            className: "btn-success",
112                            callback: function() {
113                                update_question();
114                            }
115                        },
116                        close: {
117                            label: "Cerrar",
118                            className: "btn-danger",
119                            callback: function() {}
120                        }
121                    }
122                });
123                $.each($('.bootbox-body #id_texto_pregunta_modal'),function(key,value){
124                    $(value).val(preguntas[key]['texto_pregunta']);
125                    $(value).append('<input type="hidden" name="texto_pregunta_id" value="'+preguntas[key]['id']+'">');
126                });
127                $.each($('.bootbox-body select'),function(key,value){
128                    $(value).val(preguntas[key]['tipo_pregunta']).change();
129                    if (preguntas[key]['tipo_pregunta']<=2) {
130                        var padre = $(value).parent().parent().parent().parent()
131                        var agregar_opciones = $(padre).find("#add_options");
132                        html = '<h5 class="text-success">Agregar opción '
133                        html += '<a href="#" onclick="agregar_opcion('+preguntas[key]['id']+')">';
134                        html += '<span class="glyphicon glyphicon-plus text-success"></span></a></h5>';
135                        $(agregar_opciones).append(html);
136                        html = '<div class="col-sm-12"><h5 class="text-info">Ver opciones '
137                        html += '<a href="#" onclick="see_option('+preguntas[key]['id']+')">';
138                        html += '<span class="glyphicon glyphicon-plus text-info"></span></a></h5></div>';
139                        $(padre).append(html);
140                    }
141                });
142                $.each($('.bootbox-body h4 a'),function(key,value){
143                    $(value).attr('onclick','del_pregunta(this,'+preguntas[key]['id']+')');
144                });
145            }
146            else{
147               
148            }
149        },
150        error:function(error)
151        {
152            bootbox.alert("Ocurrió un error inesperado");
153        }
154    });
155}
156
157/**
158 * Función para abrir el formulario de opciones
159 * @param id Recibe el id de la pregunta
160**/
161function agregar_opcion(id) {
162    bootbox.dialog({
163        message: $('#formulario').html(),
164        title: "Opciones",
165        buttons: {
166            success: {
167                label: "Guardar",
168                className: "btn-success",
169                callback: function() {
170                    submitOption(this);
171                }
172            },
173            close: {
174                label: "Cerrar",
175                className: "btn-danger",
176                callback: function() {}
177            }
178        }
179    });
180    $('#formulario_modal').append($('#agregar_opciones_base').html());
181    $('#formulario_modal').attr('action',id);
182}
183
184/**
185 * Función para enviar el formulario de las opciones
186**/
187function submitOption(objecto) {
188    var form = $(objecto).find('form');
189    $.ajax({
190        data: $(form).serialize(), 
191        type: 'POST',
192        url: '/administrador/consulta/create-option/'+$(form).attr('action'),
193        success: function(response) {
194            if (response.code) {
195                bootbox.alert("Se crearon las opciones con éxito");
196            }
197            else{
198                var errors = '';
199                $.each(response.errors,function(key,value){
200                    errors += key+" "+value+"<br>";
201                });
202                bootbox.alert(errors);
203            }
204        }
205    });
206}
207
208/**
209 * Función para ver las opciones de un pregunta
210 * @param id Recibe el id de la pregunta
211**/
212function see_option(id) {
213    $.ajax({
214    type: 'GET',
215    url: "/administrador/consulta/ajax/opciones-list/"+id,
216    success: function(response) {
217        if (response.success) {
218            var opciones = response.opciones;
219            var token = $('input').val();
220            var html = '<form action="" role="form" method="post" id="option_form">';
221            html += '<input type="hidden" name="csrfmiddlewaretoken" value="'+token+'">';
222            $.each(opciones,function(key,value){
223                html += "<h4>Opcion #"+parseInt(key+1)+"</h4>";
224                html+= $('#agregar_opciones').html();
225                html += "<hr>";
226            });
227            html+= '</form>';
228            bootbox.dialog({
229                message: html,
230                title: "Opciones",
231                buttons: {
232                    success: {
233                        label: "Guardar",
234                        className: "btn-success",
235                        callback: function() {
236                            update_option(id);
237                        }
238                    },
239                    close: {
240                        label: "Cerrar",
241                        className: "btn-danger",
242                        callback: function() {}
243                    }
244                }
245            });
246            $.each($('.bootbox-body #option_form #id_texto_opcion'),function(key,value){
247                $(value).val(opciones[key]['texto_opcion']);
248                $(value).append('<input type="hidden" name="texto_opcion_id" value="'+opciones[key]['id']+'">');
249            });
250            $.each($('.bootbox-body #option_form #opciones a'),function(key,value){
251                $(value).attr('onclick','del_option(this,'+opciones[key]['id']+')');
252            });
253            }
254        },
255        error:function(error)
256        {
257            bootbox.alert("Ocurrió un error inesperado");
258        }
259    });
260}
261
262/**
263 * Función para actualizar las opciones de un pregunta
264 * @param id Recibe el id de la pregunta
265**/
266function update_option(id) {
267    var form = $("#option_form");
268    $.ajax({
269        data: $(form).serialize(), 
270        type: 'POST',
271        url: '/administrador/consulta/update-option',
272        success: function(response) {
273            if (response.code) {
274                bootbox.alert("Se actualizaron las opciones con éxito");
275            }
276            else{
277                var errors = '';
278                $.each(response.errors,function(key,value){
279                    errors += key+" "+value+"<br>";
280                });
281                bootbox.alert(errors);
282            }
283        }
284    }); 
285}
286
287/**
288 * Función para eliminar las opciones de un pregunta
289 * @param id Recibe el id de la pregunta
290**/
291function del_option(element,id) {
292        bootbox.dialog({
293        message: "¿Desea borrar la opción seleccionada?",
294        title: "Alerta",
295        buttons: {
296            success: {
297                label: "Si",
298                className: "btn-success",
299                callback: function() {
300                    var token = $('input').val();
301                    $.ajax({
302                        data: {'csrfmiddlewaretoken':token},
303                        type: 'POST',
304                        url: '/administrador/consulta/delete-option/'+id,
305                        success: function(response) {
306                            if (response.success) {
307                                remove_option(element);
308                                bootbox.alert("Se eliminó la opción con éxito");
309                            }
310                            else {
311                                bootbox.alert(response.mensaje);
312                            }
313                        },
314                        error:function(error)
315                        {
316                            bootbox.alert("Ocurrió un error inesperado");
317                        }
318                    }); 
319                }
320            },
321            close: {
322                label: "No",
323                className: "btn-danger",
324                callback: function() {}
325            }
326        }
327    });
328}
329
330/**
331 * Función para eliminar una pregunta
332 * @param id Recibe el id de la pregunta
333**/
334function del_pregunta(element,id) {
335        bootbox.dialog({
336        message: "¿Desea borrar la pregunta seleccionada?",
337        title: "Alerta",
338        buttons: {
339            success: {
340                label: "Si",
341                className: "btn-success",
342                callback: function() {
343                    var token = $('input').val();
344                    $.ajax({
345                        data: {'csrfmiddlewaretoken':token},
346                        type: 'POST',
347                        url: '/administrador/consulta/delete-question/'+id,
348                        success: function(response) {
349                            if (response.success) {
350                                remove_option(element);
351                                bootbox.alert("Se eliminó la pregunta con éxito");
352                            }
353                            else {
354                                bootbox.alert(response.mensaje);
355                            }
356                        },
357                        error:function(error)
358                        {
359                            bootbox.alert("Ocurrió un error inesperado");
360                        }
361                    }); 
362                }
363            },
364            close: {
365                label: "No",
366                className: "btn-danger",
367                callback: function() {}
368            }
369        }
370    });
371}
372
373/**
374 * Función para abrir el formulario de preguntas
375 * @param id Recibe el id de la consulta
376**/
377function add_preguntas(id) {
378    var token = $('input').val();
379    var html = '<form action="" role="form" method="post" id="question_form">';
380    html += '<input type="hidden" name="csrfmiddlewaretoken" value="'+token+'">';
381    html += '<div class="content"><h5 class="text-success">Agregar Preguntas '
382    html += '<a href="#" onclick="agregar_preguntas(\'#preguntas_base\');">';
383    html += '<span class="glyphicon glyphicon-plus text-success"></span></a></h5></div>';
384    html += '<div id="agregar_preguntas">';
385    html += $('#preguntas_base').html();
386    html += '</div></form>';
387    bootbox.dialog({
388        message: html,
389        title: "Preguntas",
390        buttons: {
391            success: {
392                label: "Guardar",
393                className: "btn-success submit-question",
394                callback: function() {
395                    var vacio = false;
396                    $.each($('.modal-body #id_texto_pregunta'),function(key,value){
397                        if ($(value).val().trim()=='') {
398                            vacio = true;
399                        }
400                    });
401                    $.each($('.modal-body #id_tipo_pregunta'),function(key,value){
402                        if ($(value).val().trim()=='') {
403                            vacio = true;
404                        }
405                    });
406                    if (vacio) {
407                        event.preventDefault();
408                        bootbox.dialog({
409                            message: "Debe llenar todas las preguntas que agregó",
410                            title: "<b class='text-danger'>Error</b>",
411                            buttons: {
412                                success: {
413                                    label: "Cerrar",
414                                    className: "btn-danger",
415                                    callback: function() {}
416                                }
417                            }
418                        });
419                    }
420                    else{
421                        create_question(id);
422                    }
423                }
424            },
425            close: {
426                label: "Cerrar",
427                className: "btn-danger",
428                callback: function() {}
429            }
430        }
431    });
432}
433
434/**
435 * Función para crear un pregunta
436 * @param id Recibe el id de la consulta
437**/
438function create_question(id) {
439    var form = $("#question_form");
440    $.ajax({
441    type: 'POST',
442    data: $(form).serialize(),
443    url: "/administrador/consulta/create-question/"+id,
444    success: function(response) {
445        if (response.code) {
446            bootbox.alert("Se crearon/creó la(s) pregunta(s) con éxito");
447        }
448        else{
449            var errors = '';
450            $.each(response.errors,function(key,value){
451                errors += key+" "+value+"<br>";
452            });
453            bootbox.alert(errors);
454        }
455    },
456        error:function(error)
457        {
458            bootbox.alert("Ocurrió un error inesperado");
459        }
460    });
461}
462
463/**
464 * Función para actualizar las preguntas de una consulta
465**/
466function update_question() {
467    var form = $("#question_form");
468    $.ajax({
469        data: $(form).serialize(), 
470        type: 'POST',
471        url: '/administrador/consulta/update-question',
472        success: function(response) {
473            if (response.code) {
474                bootbox.alert("Se actualizaron las preguntas con éxito");
475            }
476            else{
477                var errors = '';
478                $.each(response.errors,function(key,value){
479                    errors += key+" "+value+"<br>";
480                });
481                bootbox.alert(errors);
482            }
483        },
484        error:function(error)
485        {
486            bootbox.alert("Ocurrió un error inesperado");
487        }
488    }); 
489}
490
491/**
492 * Función para enviar los respuestas de la encuesta
493 * @param event Recibe el evento
494**/
495function send_poll(event) {
496    event.preventDefault();
497    $('.btn-success').attr('disabled',true);
498    var form = $("#encuesta_form");
499    var routes = $(location).attr('pathname').split('/')
500    var pk = routes[routes.length-2]
501    var obj = routes[routes.length-1]
502    var participacion;
503    $.get('/participacion/ajax/validar-participacion?consulta='+pk+'&objetivo='+obj)
504    .done(function(response){
505        if (response.mensaje) {
506            participacion = response.participacion
507            if (participacion) {
508                bootbox.alert("Ya participó para esta consulta <br>Será direccionado en 4 segundos");
509                setTimeout(function(){
510                    $(location).attr('href', $(location).attr('origin')+'/participacion-busqueda/'+pk)   
511                },4000);
512            }
513            else
514            {
515                $.ajax({
516                    type: 'POST',
517                    data: $(form).serialize(),
518                    url: "/participacion/"+pk+"/"+obj,
519                    success: function(response) {
520                        if (response.code == true) {
521                            bootbox.alert("Se registró su participación con éxito <br>Será direccionado en 4 segundos");
522                            setTimeout(function(){
523                                $(location).attr('href', $(location).attr('origin')+'/participacion')   
524                            },4000);
525                        }
526                        else{
527                            bootbox.alert("Ocurrió un error inesperado");
528                            $('.btn-success').attr('disabled',false);
529                        }
530                    },
531                        error:function(error)
532                        {
533                            bootbox.alert("Ocurrió un error inesperado");
534                            $('.btn-success').attr('disabled',false);
535                        }
536                });
537            }
538        }
539        else{
540            bootbox.alert(response.error);   
541        }
542        })
543    .fail(function(response){
544        bootbox.alert("Ocurrió un error inesperado");
545    });
546}
547
548/**
549 * Función para retroceder en el carrusel y bajar el valor de la
550 * barra de progreso
551**/
552function go_back() {
553    var first_element = $('.carousel-indicators li')[0];
554    if($(first_element).attr('class')!=='active')
555    {
556        $('#myCarousel').carousel('prev');
557        var elements = $('.carousel-indicators li').length-1;
558        var current_value = ($('#status .progress-bar').width()/$('#status').width())*100;
559        var final_value = current_value-(100/elements);
560        $('#status .progress-bar').width(final_value+"%");
561        if (final_value!=100) {
562            $('#status .bar span').text() == "Finalizado" ? $('#status .bar span').text('Progreso'):'';
563            $('#status .progress-bar').removeClass('progress-bar-success');
564        }
565        if (final_value<=0) {
566            $('#status .bar span').css({'color':'black'});
567        }
568    }
569}
570
571/**
572 * Función para aumentar la barra de progreso si se responde la encuesta
573**/
574function control_progress() {
575    var content = $('.carousel-inner .active');
576    var not_empty = 0;
577    var elements = $('.carousel-indicators li').length-1;
578    $.each(content.find('input'),function(index,value){
579        var name = $(value).attr('name');
580        if(name.search('radio')!=-1 || name.search('check')!=-1 || name.search('sino')!=-1){
581            not_empty = $(value).parent().attr('class').search('checked') !== -1 ? 1:not_empty;
582            if (name.search('sino')!=-1) {
583                if ($(value).parent().attr('class').search('checked') !== -1 && $(value).val()=="No") {
584                    if ($(value).attr('class').search('need_justification')!=-1) {
585                        var text_area = $(value).parent().parent().find('textarea');
586                        not_empty = $(text_area).val().trim() !== '' ? 1:0;
587                        not_empty = $(text_area).val().length >= 10 && $(text_area).val().length <= 50  ? 1:0;
588                        if ($(text_area).val().length < 10 || $(text_area).val().length >50) {
589                            bootbox.alert("La longitud de la respuesta debe estar entre 10 y 50 cáracteres");
590                        }
591                    } 
592                }               
593            }
594        }
595    });
596    $.each(content.find('textarea'),function(index,value){
597        var name = $(value).attr('name');
598        if (name.search('abierta')!==-1) {
599            not_empty = $(value).val().trim() !== '' ? 1:not_empty;
600            not_empty = $(value).val().length >= 500 && $(value).val().length <= 2000  ? 1:0;
601            if ($(value).val().length < 500 || $(value).val().length >2000) {
602                bootbox.alert("La longitud de la respuesta debe estar entre 500 y 2000 cáracteres");
603            }
604        }
605    });
606    if (not_empty) {
607        $('#status .bar span').css({'color':'white'});
608        $('#myCarousel').carousel('next');
609        var current_value = ($('#status .progress-bar').width()/$('#status').width())*100;
610        var final_value = current_value+(100/elements);
611        $('#status .progress-bar').width(final_value+"%");
612       
613        if (final_value>=99.9) {
614            $('#status .progress-bar').width("100%");
615            $('#status .bar span').text("Finalizado");
616            $('#status .progress-bar').addClass('progress-bar-success');
617        }
618    }
619}
620
621/**
622 * Función que carga los métodos de jtable en la tabla de entes adscritos
623**/
624$(document).ready(function() {
625    $('.tabla_entes_adscritos').DataTable({
626        "language": {
627            "lengthMenu": "Mostrar _MENU_ registros por página",
628            "zeroRecords": "No hay datos",
629            "info": "Mostrando página _PAGE_ de _PAGES_",
630            "infoEmpty": "No records available",
631            "infoFiltered": "(filtered from _MAX_ total records)",
632            "search": "Buscar",
633            "paginate": {
634                "first":      "Primero",
635                "last":       "Último",
636                "next":       "Siguiente",
637                "previous":   "Anterior"
638            },
639        }
640    });
641});
642/*
643 * Función para crear el pre-procesamiento por ajax
644 * @param {object} form Recibe el formulario
645 */
646function createPreprocess(form) {
647    bootbox.alert("Se le notifcará cuando finalice el pre-procesamiento");
648    $.ajax({ // create an AJAX call...
649        data: $(form).serialize(), // get the form data
650        type: $(form).attr('method'), // GET or POST
651        url: $(form).attr('action'), // the file to call
652        success: function(response) { // on success..
653            if (response.code) {
654                bootbox.alert("Se finalizó con éxito");
655            }
656            else{
657                $('.container').html(response);
658            }
659        }
660    });
661}
662
663/**
664 * Función para traer el listado de tópicos
665 * @param {object} element Recibe el elemento
666 * @param {object} event Recibe el evento
667 * @param {int} id Recibe el id del procesamiento
668 */
669function visualize(element,event,id) {
670    event.preventDefault();
671    $('#status').show(500);
672    var text = $(element).text();
673    var number = text.split(" ")[0]
674    $('#visualize').text(text);
675    var url = '/administrador/visualizacion/generate_topics/'+id+"/"+number;
676    $.get(url,function(data){
677        if (data) {
678            $('#topicos').html('');
679            $.each(data,function(index,value){
680                var words_ordered = Object.keys(value.words).sort(function(a,b){return value.words[b]-value.words[a];});
681                var html = "<div class='panel panel-default'>";
682                var url = '/administrador/visualizacion/topic/'+id+'/'+number+'/'+index;
683                html += "<div class='panel-heading' style='background-color:"+value.color+"'>";
684                html += "Tópico #"+index;
685                html += "</div><div class='panel-body'>";
686                html += words_ordered.join(", ");
687                html += "</div><div class='panel-footer'>";
688                html += "<a type='button' class='btn btn-default' href='"+url+"'>Ver Documentos para Tópico #"+index+"</a>"
689                html += "</div></div>";
690                $('#topicos').append(html);
691                $('#status .progress-bar').addClass('progress-bar-success').css("width","100%").attr("aria-valuenow","100").text("Completado!");
692            });
693            $('#status').hide(2000);
694        }
695        else
696        {
697            $('#status .progress-bar').removeClass('active progress-bar-striped').text('No se pudieron cargar los tópicos.');
698        }
699    });
700}
701
702/**
703 * Función que despliega el modal para crear los archivos de respuesta
704 * de la consulta
705 */
706function create_files(){
707    var routes = $(location).attr('pathname').split('/')
708    var pk = routes[routes.length-1];
709    var html = '';
710    $.ajax({
711        type: 'GET',
712        url: "/administrador/consulta/ajax/valid-dir/"+pk,
713        success: function(response) {
714            if (response.code == true) {
715                html+= "El directorio existe, ¿desea sobreescribirlo?";
716            }
717            else{
718                html+= "El directorio no existe, ¿desea crearlo?";
719            }
720            bootbox.dialog({
721                message: html,
722                title: "Generar Texto de Respuestas",
723                buttons: {
724                    success: {
725                        label: "Si",
726                        className: "btn-success",
727                        callback: function() {
728                            create_text_files(pk);
729                        }
730                    },
731                    close: {
732                        label: "No",
733                        className: "btn-danger",
734                        callback: function() {}
735                    }
736                }
737            });
738        },
739        error:function(error){
740                bootbox.alert("Ocurrió un error inesperado");
741        }
742    });
743}
744
745/**
746 * Función que crea los textos
747 */
748function create_text_files(pk){
749    $.ajax({
750        type: 'GET',
751        url: "/administrador/consulta/ajax/generar-textos-respuesta/"+pk,
752        success: function(response) {
753            bootbox.alert(response.mensaje);
754        },
755        error:function(error){
756                bootbox.alert("Ocurrió un error inesperado");
757        }
758    });
759}
760
761
762/**
763 * @brief Función que actualiza los datos de combos dependientes
764 * @param opcion Código del elemento seleccionado por el cual se filtrarán los datos en el combo dependiente
765 * @param app Nombre de la aplicación en la cual buscar la información a filtrar
766 * @param mod Modelo del cual se van a extraer los datos filtrados según la selección
767 * @param campo Nombre del campo con el cual realizar el filtro de los datos
768 * @param n_value Nombre del campo que contendra el valor de cada opción en el combo
769 * @param n_text Nombre del campo que contendrá el texto en cada opción del combo
770 * @param combo_destino Identificador del combo en el cual se van a mostrar los datos filtrados
771 * @param bd Nombre de la base de datos, si no se específica se asigna el valor por defecto
772 */
773function actualizar_combo(opcion, app, mod, campo, n_value, n_text, combo_destino, bd) {
774    /* Verifica si el parámetro esta definido, en caso contrario establece el valor por defecto */
775    bd = typeof bd !== 'undefined' ? bd : 'default';
776    $.ajaxSetup({
777        async: false
778    });
779    $.getJSON('/ajax/actualizar-combo/', {
780        opcion:opcion, app:app, mod:mod, campo:campo, n_value:n_value, n_text: n_text, bd:bd
781    }, function(datos) {
782
783        var combo = $("#"+combo_destino);
784
785        if (datos.resultado) {
786
787            if (datos.combo_disabled == "false") {
788                combo.removeAttr("disabled");
789            }
790            else {
791                combo.attr("disabled", "true");
792            }
793
794            combo.html(datos.combo_html);
795        }
796        else {
797            bootbox.alert(datos.error);
798            console.log(datos.error);
799        }
800    }).fail(function(jqxhr, textStatus, error) {
801        var err = textStatus + ", " + error;
802        bootbox.alert( 'Petición fállida' + err );
803        console.log('Petición fállida ' + err)
804    });
805}
806
807/**
808 * @brief Función para recargar el captcha vía json
809 * @param element Recibe el botón
810 */
811function refresh_captcha(element) {
812    $form = $(element).parents('form');
813    var url = location.protocol + "//" + window.location.hostname + ":" + location.port + "/captcha/refresh/";
814
815    $.getJSON(url, {}, function(json) {
816        $form.find('input[name="captcha_0"]').val(json.key);
817        $form.find('img.captcha').attr('src', json.image_url);
818    });
819
820    return false;
821}
822
823/**
824 * @brief Función para mostrar un campo
825 * @param valor Recibe el valor
826 * @param condicion Recibe la condición a evaluar
827 * @param element Recibe el elemento a habilitar
828 */
829function mostrar(valor,condicion,element) {
830    if (valor==condicion) {
831        $('#'+element).show();
832    }
833    else{
834        $('#'+element).hide();
835    }
836}
837
838/**
839 * @brief Función para habilitar/deshabilitar un campo
840 * @param valor Recibe el valor
841 * @param condicion Recibe la condición a evaluar
842 * @param element Recibe el elemento a modificar
843 * @param attr_name Recibe el nombre del atributo a agregar/remover
844 */
845function habilitar(valor,condicion,element,attr_name) {
846    if (valor!=condicion) {
847        $('#'+element).attr(attr_name,true)
848    }
849    else{
850        $('#'+element).removeAttr(attr_name);
851    }
852}
853
854/**
855 * @brief Función para mostrar los sectores
856 * @param valor Recibe el valor
857 */
858function mostrar_sector(valor) {
859    mostrar(valor,'ES','sector_estudiante');
860    mostrar(valor,'TR','sector_trabajador'); 
861}
862
863/**
864 * @brief Función para validar si pertenece a un colectivo
865 * @param valor Recibe el valor
866 */
867function habilitar_colectivo(valor) {
868    habilitar(valor,'CO','id_colectivo','readonly');
869}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.