JavaScript - Sumar agrupadamente lineas de html

 
Vista:

Sumar agrupadamente lineas de html

Publicado por Roberto (11 intervenciones) el 31/01/2018 09:36:09
Buenas. Necesito para un proyecto del trabajo poder sumar por grupos los detalles de un presupuesto.
Necesito poder mostrar los totales antes de grabar el presupuesto asi que todo lo que tengo que sumar es html.
Ejemplo.

REFERENCIA DESCRIPCION PRECIO CANTIDAD SUBTOTAL
articulo1 ------------------- 2.5 1 2.5
articulo2 ----------------- 3 1 3
articulo3 ---------------- 4 1 4
OPCION1
articulo1 ----------------- 2.5 1 2.5
articulo2 ----------------- 3 1 3
OPCION2
articulo3 ---------------- 4 1 4
articulo1 ---------------- 2.5 1 2.5

TOTAL (sin sumar la OPCION1 Y OPCION2) ........................................9.5
TOTAL OPCION1 .......................................... 5.5
TOTAL OPCION2 .......................................... 6.5

El problema es que no se muy bien como hacer este agrupamiento. Recorrer todas las lineas de html y como saber que unas pertenecen al grupo OPCION1 u OPCION2 o a ninguno. OPCION1 y OPCION2 son inputs con id='titulo' que se muestran o no dependiendo de si se activa la opcion titulo con un boton. El resto son inputs del tipo REFERENCIA, DESCRIPCION, PRECIO, CANTIDAD, SUBTOTAL.
No se me ocurre como hacerlo. Gracias a todos.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de santi
Val: 30
Ha disminuido 1 puesto en JavaScript (en relación al último mes)
Gráfica de JavaScript

Sumar agrupadamente lineas de html

Publicado por santi (12 intervenciones) el 02/02/2018 03:32:31
Hola,

añade el código o adjunta el archivo para saber más...
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de ezequiel
Val: 13
Ha aumentado 1 puesto en JavaScript (en relación al último mes)
Gráfica de JavaScript

Sumar agrupadamente lineas de html

Publicado por ezequiel (6 intervenciones) el 02/02/2018 16:24:36
Sin el código de referencia es dificil ayudarte. No entiendo exactamente porque pusiste los títulos con inputs, en todo caso podrías recolectar todos los datos del formulario en un array, y luego buscar la posición de la palabra OPCION2 con indexOf y guardar su posición en una variable, luego ya sabrás que todos los que están guardados en una posición inferior a la posición de OPCION2 pertenecen a la OPCION1 y los que estén guardados en posiciones superiores pertenecen a la OPCION2.
Igual por ahi estoy errando ya que por ahi no entendi bien lo que estas tratando de hacer. Adjunta tu código.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Sumar agrupadamente lineas de html

Publicado por ROBERTO (11 intervenciones) el 05/02/2018 09:19:58
Cada vez que añado un detalle con un boton de + ejecuto esta funcion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
function add_detalle(REFERENCIA, CANTIDAD, PRECIO, DTO1, DTO2, DTO3, DTOX, OFERTA, TITULO, SUBTITULO){
        // Sumamos uno mas al control de cantidad de lineas
        console.log("NumLineas (Antes) -> "+ $("#NUM_LINEAS").val());
 
        $("#NUM_LINEAS").val(parseInt($("#NUM_LINEAS").val()) + parseInt(1))
        var N_LINEA = $("#NUM_LINEAS").val();
 
 
 
        // Si las variables vienen vacias, las definimos a cero
        if(typeof REFERENCIA == 'undefined') REFERENCIA = '';
        if(typeof CANTIDAD == 'undefined') CANTIDAD = '1';
        if(typeof PRECIO == 'undefined') PRECIO = '0';
        if(typeof DTO1 == 'undefined') DTO1 = $('#DTO1').val();
        if(typeof DTO2 == 'undefined') DTO2 = $('#DTO2').val();
        if(typeof DTO3 == 'undefined') DTO3 = $('#DTO3').val();
        if(typeof DTOX == 'undefined') DTOX = 0;
        if(typeof OFERTA == 'undefined') OFERTA = '';
        var ORDEN = N_LINEA;
        if(typeof TITULO == 'undefined') TITULO = '';
        if(typeof SUBTITULO == 'undefined') SUBTITULO = "";
 
        //if($('#TIPO_LINEA_'+N_LINEA+).val()=='OPCIONAL'){CLASE_BLOQUE ='OPCIONAL'}
        //if($('#TIPO_LINEA_'+N_LINEA+).val()=='OPCION1'){CLASE_BLOQUE ='OPCION1'}
        //if($('#TIPO_LINEA_'+N_LINEA+).val()=='OPCION2'){CLASE_BLOQUE ='OPCION2'}
 
        // Añadimos uno nuevo con el contenido indicado (en caso de que venga
        var strInnerHTML = "<input type='hidden' id='TIPO_LINEA_"+N_LINEA+"' name='TIPO_LINEA_"+N_LINEA+"' value='r' /> \
                                        <input type='hidden' id='ORDEN_"+N_LINEA+"' name='ORDEN_"+N_LINEA+"' value='"+ORDEN+"' /> \
                                        <input type='hidden' id='OFERTA_"+N_LINEA+"' name='OFERTA_"+N_LINEA+"' value='"+OFERTA+"' /> \
                <div id='CMB_TIPO_LINEA_"+N_LINEA+"' class='tgl_lista_tipo_linea tipo_ref' onclick='Toggle(\"cmb_tipo_linea_"+N_LINEA+"\")'></div>\
                <div id='cmb_tipo_linea_"+N_LINEA+"' class='content_lista_tipo_linea'>\
                        <div class='lista_sel_tipo tipo_ref' onclick='tipo(\""+N_LINEA+"\", \"r\"); Toggle(\"cmb_tipo_linea_"+N_LINEA+"\");'></div>\
                        <div class='lista_sel_tipo tipo_tit' onclick='tipo(\""+N_LINEA+"\", \"t\"); Toggle(\"cmb_tipo_linea_"+N_LINEA+"\");'></div>\
                        <div class='lista_sel_tipo tipo_sbt' onclick='tipo(\""+N_LINEA+"\", \"s\"); Toggle(\"cmb_tipo_linea_"+N_LINEA+"\");'></div>\
                </div>\
                <div class='linea_tit' id='div_titulo_"+N_LINEA+"' name='div_titulo_"+N_LINEA+"'> \
                        <input id='TITULO_"+N_LINEA+"' name='TITULO_"+N_LINEA+"' class='input_titulo' onKeyUp='detectar_tipo_linea(event, "+N_LINEA+")' value='"+TITULO+"'/>\
                </div>\
                <div class='linea_sbt' id='div_subtitulo_"+N_LINEA+"' name='div_subtitulo_"+N_LINEA+"'> \
                        <input id='SUBTITULO_"+N_LINEA+"' name='SUBTITULO_"+N_LINEA+"' class='input_subtitulo' onKeyUp='detectar_tipo_linea(event, "+N_LINEA+")' value='"+SUBTITULO+"'/> \
                </div>\
                <div class='linea_ref' id='div_referencia_"+N_LINEA+"' name='div_referencia_"+N_LINEA+"'>\
                        <div class='col col_referencia'>\
                                <input type='text' id='REFERENCIA_"+N_LINEA+"' name='REFERENCIA_"+N_LINEA+"' \
                                        onKeyUp='detectar_tipo_linea(event, "+N_LINEA+")' \
                                        onchange='window.setTimeout(function(){calcular_datos_ref("+N_LINEA+")}, 500)' \
                                        style='width:90px;' \
                                        class='autocompletar_ref_publicas' \
                                        value='"+REFERENCIA+"'/>\
                                <div class='ver' onclick='ver_ref("+N_LINEA+")'></div>\
                                <div class='lupa' onclick='modal_buscar_ref("+N_LINEA+")' style='float:right; margin-right: 5px;'></div>\
                        </div>\
                        <div class='col col_descripcion'>\
                                <input type='text' id='DESCRIPCION_"+N_LINEA+"' name='DESCRIPCION_"+N_LINEA+"' style='width:190px;' value='"+TITULO+"'/> \
                        </div>\
                        <div class='col col_precio'>		\
                                <input type='text' id='PRECIO_"+N_LINEA+"' name='PRECIO_"+N_LINEA+"' size='8' style='width:50px;' value='"+PRECIO+"'/>\
                                <div class='lupa' onclick='modal_buscar_precios("+N_LINEA+")' style='float:right;'></div>\
                        </div>\
                        <div class='col col_cantidad'>		<input type='text' id='CANTIDAD_"+N_LINEA+"' name='CANTIDAD_"+N_LINEA+"' size='3' value = '"+CANTIDAD+"' onKeyUp='calcular_totales()' onBlur='comprobar_stock(this, "+N_LINEA+");'/> Ud.</div>\
                        <div class='col col_descuento'>		<input type='text' id='DTO1_"+N_LINEA+"' name='DTO1_"+N_LINEA+"' size='3' value = '"+DTO1+"' onchange='calcular_totales()'/></div>\
                        <div class='col col_descuento'>		<input type='text' id='DTO2_"+N_LINEA+"' name='DTO2_"+N_LINEA+"' size='3' value = '"+DTO2+"' onchange='calcular_totales()'/></div>\
                        <div class='col col_descuento'>		<input type='text' id='DTO3_"+N_LINEA+"' name='DTO3_"+N_LINEA+"' size='3' value = '"+DTO3+"' onchange='calcular_totales()'/></div>\
                        <div class='col col_descuento'>		<input type='text' id='DTOX_"+N_LINEA+"' name='DTOX_"+N_LINEA+"' size='3' value = '"+DTOX+"' onchange='calcular_totales()'/></div>\
                        <div class='col col_subtotal'>		<div class='subtotal' id='SUBTOTAL_"+N_LINEA+"'>0 €</div></div>\
                </div>\
                <div class='col col_del'>\
                    <input type='checkbox' class='seleccionable' n-linea='"+N_LINEA+"'> \
                </div>";
 
 
 
        //alert($("input").prev(".autocompletar_ref_publicas").html());
 
        var li=document.createElement('LI');
        li.id = "LI_DETALLE_"+N_LINEA;
        li.className = "linea_detalle";
        li.style = "";
        li.innerHTML=strInnerHTML;
 
        // Si el foco está en una linea intermedia, cargamos la variable COLOCACION para hacer un ".after()"
 
        // TODO: Calcular el ID del LI que lo contiene
        var id_anterior = $("#"+lastFocusedElement).closest('li').attr('id');
 
        //alert("LAST: "+lastFocusedElement+ " - ID anterior: "+id_anterior);
        // Si se encuentra el id anterior, se añade justo despues, y si no al final
        if(typeof id_anterior == 'undefined'){
            var ul = document.getElementById("detalle_press")
 
            ul.appendChild(li);
 
        }else{
            $("#"+id_anterior).after(li);
 
            // Recalculamos el orden "oficial"
            reordenar_detalles();
 
            // Generamos de nuevo el disparador de evento que carga en memoria el ultimo ID
            $("input").focusout(function() {
                lastFocusedElement = $(this).attr("id");
                //window.document.title = lastFocusedElement;
            });
 
        }
 
 
        // Cargamos el tipo de linea segun corresponda
        if (REFERENCIA=='*'){
            var TIPO='t';
        }else if (REFERENCIA=='.'){
            var TIPO = "s";
        }else{
            var TIPO = "r";
        }
 
        tipo(N_LINEA, TIPO);
        recalcular_autocompletes();
 
    console.log("NumLineas (Al FINAL) -> "+$("#NUM_LINEAS").val());
}



La funcion calcular_totales la tengo en otro fichero js.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
function calcular_totales(){
 
        var TOTAL = 0;
        var NLineas = $("#NUM_LINEAS").val();
 
        for (N_LINEA=1; N_LINEA<=NLineas; N_LINEA++){
            if (document.getElementById('CANTIDAD_'+N_LINEA)){
 
                // Para hacer calculos debe ser de tipo referencia
                if ($('#TIPO_LINEA_'+N_LINEA).val() == 'r'){
                    var UPP = $('#REFERENCIA_'+N_LINEA).val().toUpperCase();
                    //alert(UPP)
                    $('#REFERENCIA_'+N_LINEA).val(UPP);
 
                    objCantidad =document.getElementById('CANTIDAD_'+N_LINEA);
                    Cantidad = objCantidad.value;
                    if (isNaN(Cantidad)) Cantidad = 0;
 
                    //Quitamos posibles comas
                    neoPrecio=$("#PRECIO_"+N_LINEA).val();
                    neoPrecio=neoPrecio.replace(",", "")
                    $("#PRECIO_"+N_LINEA).val(neoPrecio);
                    //alert(neoPrecio)
 
                    Precio = document.getElementById('PRECIO_'+N_LINEA).value;
                    if (isNaN(Precio)) Precio = 0;
 
                    if (Precio<0.001) $('#PRECIO_'+N_LINEA).effect('highlight', '', 5000);
 
                    SubTotal = parseFloat(Cantidad) * parseFloat(Precio);
                    if (isNaN(SubTotal)) SubTotal = 0;
 
                    // Descuentos
                    DTO1 = document.getElementById('DTO1_'+N_LINEA).value;
                    DTO2 = document.getElementById('DTO2_'+N_LINEA).value;
                    DTO3 = document.getElementById('DTO3_'+N_LINEA).value;
                    DTOX = document.getElementById('DTOX_'+N_LINEA).value;
 
                    if (parseFloat(DTO1)>0) SubTotal = parseFloat(SubTotal) - parseFloat(parseFloat(SubTotal)*parseFloat(DTO1))/100
                    if (parseFloat(DTO2)>0) SubTotal = parseFloat(SubTotal) - parseFloat(parseFloat(SubTotal)*parseFloat(DTO2))/100
                    if (parseFloat(DTO3)>0) SubTotal = parseFloat(SubTotal) - parseFloat(parseFloat(SubTotal)*parseFloat(DTO3))/100
                    if (parseFloat(DTOX)>0) SubTotal = parseFloat(SubTotal) - parseFloat(parseFloat(SubTotal)*parseFloat(DTOX))/100
 
                    TOTAL = parseFloat(TOTAL) + parseFloat(SubTotal);
                    SubTotal = parseFloat(SubTotal).toFixed(2);
 
                    document.getElementById('SUBTOTAL_'+N_LINEA).innerHTML = SubTotal + " €";
 
                }
            }
        }
 
 
        // Sumamos los Portes
        TOTAL = parseFloat(TOTAL).toFixed(2);
        document.getElementById("TOTAL_SINPORTES").innerHTML = TOTAL + " €";
 
        // Calculamos el Pronto Pago si corresponde
        PCT_PPAGO = parseFloat(Math.abs($("#PRONTO_PAGO").val()));
        if (PCT_PPAGO>0){
                PPAGO = (PCT_PPAGO * TOTAL) / 100;
                if (isNaN(PPAGO)) PPAGO = 0;
                PPAGO = PPAGO.toFixed(2);
                document.getElementById("PPAGO").innerHTML = "- " + PPAGO + " €";
                $("#LN_PPAGO").show();
        }else{
                PPAGO = 0;
                $("#LN_PPAGO").hide();
        }
 
        // Calculamos el Pronto Pago si corresponde
 
 
        // Sumamos portes
        PORTES = parseFloat(document.getElementById("PORTES").value);
        if (isNaN(PORTES)) PORTES = 0;
        if (PORTES>0){
                PORTES = PORTES.toFixed(2);
                document.getElementById("PPORTES").innerHTML = PORTES + " €";
                $("#LN_PORTES").show();
        }else{
                $("#LN_PORTES").hide();
        }
 
        TOTAL = parseFloat(TOTAL) + parseFloat(PORTES) - parseFloat(PPAGO);
        TOTAL = parseFloat(TOTAL).toFixed(2);
        document.getElementById("TOTAL").innerHTML = TOTAL + " €";
 
        //alert(0)
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar