source: consulta_publica/static/js/funciones.js @ 59f3e60

constituyenteestudiantesgeneralplan_patriasala
Last change on this file since 59f3e60 was bcf369a, checked in by rudmanmrrod <rudman22@…>, 7 años ago

Agregados cambios para adaptar la consulta a la sala situacional

  • Propiedad mode establecida a 100644
File size: 30.3 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-red",
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-primary",
112                            callback: function() {
113                                update_question();
114                            }
115                        },
116                        close: {
117                            label: "Cerrar",
118                            className: "btn-red",
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-primary",
169                callback: function() {
170                    submitOption(this);
171                }
172            },
173            close: {
174                label: "Cerrar",
175                className: "btn-red",
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-primary",
235                        callback: function() {
236                            update_option(id);
237                        }
238                    },
239                    close: {
240                        label: "Cerrar",
241                        className: "btn-red",
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-primary",
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-red",
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-primary",
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-red",
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-primary 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-red",
415                                    callback: function() {}
416                                }
417                            }
418                        });
419                    }
420                    else{
421                        create_question(id);
422                    }
423                }
424            },
425            close: {
426                label: "Cerrar",
427                className: "btn-red",
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-primary').attr('disabled',true);
498    var form = $("#encuesta_form");
499    var routes = $(location).attr('pathname').split('/');
500    if (routes.length==4) {
501        var pk = routes[routes.length-2];
502        var obj = routes[routes.length-1];
503    }
504    else{
505        var pk = routes[routes.length-1];
506        var obj = pk;
507    }
508    var participacion;
509    $.get('/participacion/ajax/validar-participacion?consulta='+pk+'&objetivo='+obj)
510    .done(function(response){
511        if (response.mensaje) {
512            participacion = response.participacion
513            if (participacion) {
514                bootbox.alert("Ya participó para esta consulta <br>Será direccionado en 4 segundos");
515                setTimeout(function(){
516                    $(location).attr('href', $(location).attr('origin')+'/participacion')   
517                },4000);
518            }
519            else
520            {
521                $.ajax({
522                    type: 'POST',
523                    data: $(form).serialize(),
524                    url: "/participacion/"+pk+"/"+obj,
525                    success: function(response) {
526                        if (response.code == true) {
527                            bootbox.alert("Se registró su participación con éxito <br>Será direccionado en 4 segundos");
528                            setTimeout(function(){
529                                $(location).attr('href', $(location).attr('origin')+'/participacion')   
530                            },4000);
531                        }
532                        else{
533                            bootbox.alert("Ocurrió un error inesperado");
534                            $('.btn-primary').attr('disabled',false);
535                        }
536                    },
537                        error:function(error)
538                        {
539                            bootbox.alert("Ocurrió un error inesperado");
540                            $('.btn-primary').attr('disabled',false);
541                        }
542                });
543            }
544        }
545        else{
546            bootbox.alert(response.error);   
547        }
548        })
549    .fail(function(response){
550        bootbox.alert("Ocurrió un error inesperado");
551    });
552}
553
554/**
555 * Función para retroceder en el carrusel y bajar el valor de la
556 * barra de progreso
557**/
558function go_back() {
559    var first_element = $('.carousel-indicators li')[0];
560    if($(first_element).attr('class')!=='active')
561    {
562        $('#myCarousel').carousel('prev');
563        var elements = $('.carousel-indicators li').length-1;
564        var current_value = ($('#status .progress-bar').width()/$('#status').width())*100;
565        var final_value = current_value-(100/elements);
566        $('#status .progress-bar').width(final_value+"%");
567        if (final_value!=100) {
568            $('#status .bar span').text() == "Finalizado" ? $('#status .bar span').text('Progreso'):'';
569            $('#status .progress-bar').removeClass('progress-bar-success');
570        }
571        if (final_value<=0) {
572            $('#status .bar span').css({'color':'black'});
573        }
574    }
575}
576
577/**
578 * Función para aumentar la barra de progreso si se responde la encuesta
579**/
580function control_progress() {
581    var content = $('.carousel-inner .active');
582    var not_empty = 0;
583    var elements = $('.carousel-indicators li').length-1;
584    $.each(content.find('input'),function(index,value){
585        var name = $(value).attr('name');
586        if(name.search('radio')!=-1 || name.search('check')!=-1 || name.search('sino')!=-1){
587            not_empty = $(value).parent().attr('class').search('checked') !== -1 ? 1:not_empty;
588            if (name.search('sino')!=-1) {
589                if ($(value).parent().attr('class').search('checked') !== -1 && $(value).val()=="Si") {
590                    if ($(value).attr('class').search('need_justification')!=-1) {
591                        var text_area = $(value).parent().parent().find('textarea');
592                        not_empty = $(text_area).val().trim() !== '' ? 1:0;
593                        not_empty = $(text_area).val().length >= 10 && $(text_area).val().length <= 50  ? 1:0;
594                        if ($(text_area).val().length < 10 || $(text_area).val().length >50) {
595                            bootbox.alert("La longitud de la respuesta debe estar entre 10 y 50 cáracteres");
596                        }
597                    } 
598                }               
599            }
600        }
601    });
602    $.each(content.find('textarea'),function(index,value){
603        var name = $(value).attr('name');
604        if (name.search('abierta')!==-1) {
605            not_empty = $(value).val().trim() !== '' ? 1:not_empty;
606            not_empty = $(value).val().length >= 700 && $(value).val().length <= 5000  ? 1:0;
607            if ($(value).val().length < 700 || $(value).val().length >5000) {
608                bootbox.alert("La longitud de la respuesta debe estar entre 700 y 5000 cáracteres");
609            }
610        }
611    });
612    if (not_empty) {
613        $('#status .bar span').css({'color':'white'});
614        $('#myCarousel').carousel('next');
615        var current_value = ($('#status .progress-bar').width()/$('#status').width())*100;
616        var final_value = current_value+(100/elements);
617        $('#status .progress-bar').width(final_value+"%");
618       
619        if (final_value>=99.9) {
620            $('#status .progress-bar').width("100%");
621            $('#status .bar span').text("Finalizado");
622            $('#status .progress-bar').addClass('progress-bar-success');
623        }
624    }
625}
626
627/**
628 * Función que carga los métodos de jtable en la tabla de entes adscritos
629**/
630$(document).ready(function() {
631    $('.tabla_entes_adscritos').DataTable({
632        "language": {
633            "lengthMenu": "Mostrar _MENU_ registros por página",
634            "zeroRecords": "No hay datos",
635            "info": "Mostrando página _PAGE_ de _PAGES_",
636            "infoEmpty": "No records available",
637            "infoFiltered": "(filtered from _MAX_ total records)",
638            "search": "Buscar",
639            "paginate": {
640                "first":      "Primero",
641                "last":       "Último",
642                "next":       "Siguiente",
643                "previous":   "Anterior"
644            },
645        }
646    });
647});
648/*
649 * Función para crear el pre-procesamiento por ajax
650 * @param {object} form Recibe el formulario
651 */
652function createPreprocess(form) {
653    bootbox.alert("Se le notifcará cuando finalice el pre-procesamiento");
654    $.ajax({ // create an AJAX call...
655        data: $(form).serialize(), // get the form data
656        type: $(form).attr('method'), // GET or POST
657        url: $(form).attr('action'), // the file to call
658        success: function(response) { // on success..
659            if (response.code) {
660                bootbox.alert("Se finalizó con éxito");
661            }
662            else{
663                $('.container').html(response);
664            }
665        }
666    });
667}
668
669/**
670 * Función para traer el listado de tópicos
671 * @param {object} element Recibe el elemento
672 * @param {object} event Recibe el evento
673 * @param {int} id Recibe el id del procesamiento
674 */
675function visualize(element,event,id) {
676    event.preventDefault();
677    $('#status').show(500);
678    var text = $(element).text();
679    var number = text.split(" ")[0]
680    $('#visualize').text(text);
681    var url = '/administrador/visualizacion/generate_topics/'+id+"/"+number;
682    $.get(url,function(data){
683        if (data) {
684            $('#topicos').html('');
685            $.each(data,function(index,value){
686                var words_ordered = Object.keys(value.words).sort(function(a,b){return value.words[b]-value.words[a];});
687                var html = "<div class='panel panel-default'>";
688                var url = '/administrador/visualizacion/topic/'+id+'/'+number+'/'+index;
689                html += "<div class='panel-heading' style='background-color:"+value.color+"'>";
690                html += "Tópico #"+index;
691                html += "</div><div class='panel-body'>";
692                html += words_ordered.join(", ");
693                html += "</div><div class='panel-footer'>";
694                html += "<a type='button' class='btn btn-default' href='"+url+"'>Ver Documentos para Tópico #"+index+"</a>"
695                html += "</div></div>";
696                $('#topicos').append(html);
697                $('#status .progress-bar').addClass('progress-bar-success').css("width","100%").attr("aria-valuenow","100").text("Completado!");
698            });
699            $('#status').hide(2000);
700        }
701        else
702        {
703            $('#status .progress-bar').removeClass('active progress-bar-striped').text('No se pudieron cargar los tópicos.');
704        }
705    });
706}
707
708/**
709 * Función que despliega el modal para crear los archivos de respuesta
710 * de la consulta
711 */
712function create_files(){
713    var routes = $(location).attr('pathname').split('/')
714    var pk = routes[routes.length-1];
715    var html = '';
716    $.ajax({
717        type: 'GET',
718        url: "/administrador/consulta/ajax/valid-dir/"+pk,
719        success: function(response) {
720            if (response.code == true) {
721                html+= "El directorio existe, ¿desea sobreescribirlo?";
722            }
723            else{
724                html+= "El directorio no existe, ¿desea crearlo?";
725            }
726            bootbox.dialog({
727                message: html,
728                title: "Generar Texto de Respuestas",
729                buttons: {
730                    success: {
731                        label: "Si",
732                        className: "btn-primary",
733                        callback: function() {
734                            create_text_files(pk);
735                        }
736                    },
737                    close: {
738                        label: "No",
739                        className: "btn-red",
740                        callback: function() {}
741                    }
742                }
743            });
744        },
745        error:function(error){
746                bootbox.alert("Ocurrió un error inesperado");
747        }
748    });
749}
750
751/**
752 * Función que crea los textos
753 */
754function create_text_files(pk){
755    $.ajax({
756        type: 'GET',
757        url: "/administrador/consulta/ajax/generar-textos-respuesta/"+pk,
758        success: function(response) {
759            bootbox.alert(response.mensaje);
760        },
761        error:function(error){
762                bootbox.alert("Ocurrió un error inesperado");
763        }
764    });
765}
766
767
768/**
769 * @brief Función que actualiza los datos de combos dependientes
770 * @param opcion Código del elemento seleccionado por el cual se filtrarán los datos en el combo dependiente
771 * @param app Nombre de la aplicación en la cual buscar la información a filtrar
772 * @param mod Modelo del cual se van a extraer los datos filtrados según la selección
773 * @param campo Nombre del campo con el cual realizar el filtro de los datos
774 * @param n_value Nombre del campo que contendra el valor de cada opción en el combo
775 * @param n_text Nombre del campo que contendrá el texto en cada opción del combo
776 * @param combo_destino Identificador del combo en el cual se van a mostrar los datos filtrados
777 * @param bd Nombre de la base de datos, si no se específica se asigna el valor por defecto
778 */
779function actualizar_combo(opcion, app, mod, campo, n_value, n_text, combo_destino, bd) {
780    /* Verifica si el parámetro esta definido, en caso contrario establece el valor por defecto */
781    bd = typeof bd !== 'undefined' ? bd : 'default';
782    $.ajaxSetup({
783        async: false
784    });
785    $.getJSON('/ajax/actualizar-combo/', {
786        opcion:opcion, app:app, mod:mod, campo:campo, n_value:n_value, n_text: n_text, bd:bd
787    }, function(datos) {
788
789        var combo = $("#"+combo_destino);
790
791        if (datos.resultado) {
792
793            if (datos.combo_disabled == "false") {
794                combo.removeAttr("disabled");
795            }
796            else {
797                combo.attr("disabled", "true");
798            }
799
800            combo.html(datos.combo_html);
801        }
802        else {
803            bootbox.alert(datos.error);
804            console.log(datos.error);
805        }
806    }).fail(function(jqxhr, textStatus, error) {
807        var err = textStatus + ", " + error;
808        bootbox.alert( 'Petición fállida' + err );
809        console.log('Petición fállida ' + err)
810    });
811}
812
813/**
814 * @brief Función para recargar el captcha vía json
815 * @param element Recibe el botón
816 */
817function refresh_captcha(element) {
818    $form = $(element).parents('form');
819    var url = location.protocol + "//" + window.location.hostname + ":" + location.port + "/captcha/refresh/";
820
821    $.getJSON(url, {}, function(json) {
822        $form.find('input[name="captcha_0"]').val(json.key);
823        $form.find('img.captcha').attr('src', json.image_url);
824    });
825
826    return false;
827}
828
829/**
830 * @brief Función para mostrar un campo
831 * @param valor Recibe el valor
832 * @param condicion Recibe la condición a evaluar
833 * @param element Recibe el elemento a habilitar
834 */
835function mostrar(valor,condicion,element) {
836    if (valor==condicion) {
837        $('#'+element).show();
838    }
839    else{
840        $('#'+element).hide();
841    }
842}
843
844/**
845 * @brief Función para habilitar/deshabilitar un campo
846 * @param valor Recibe el valor
847 * @param condicion Recibe la condición a evaluar
848 * @param element Recibe el elemento a modificar
849 * @param attr_name Recibe el nombre del atributo a agregar/remover
850 */
851function habilitar(valor,condicion,element,attr_name) {
852    if (valor!=condicion) {
853        $('#'+element).attr(attr_name,true)
854    }
855    else{
856        $('#'+element).removeAttr(attr_name);
857    }
858}
859
860/**
861 * @brief Función para mostrar los sectores
862 * @param valor Recibe el valor
863 */
864function mostrar_sector(valor) {
865    mostrar(valor,'ES','sector_estudiante');
866    mostrar(valor,'TR','sector_trabajador'); 
867}
868
869/**
870 * @brief Función para validar si pertenece a un colectivo
871 * @param valor Recibe el valor
872 */
873function habilitar_colectivo(valor) {
874    habilitar(valor,'CO','id_colectivo','readonly');
875}
876
877function medir_caracters(obj) {
878    var span = $(obj).parent().find('#longitud span');
879    span.text($(obj).val().length);
880}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.