Jquery recopila atributos para montar (números)

I have a list (ul list) and every li item has a 'data-pret' . I want to collect from li who has the class '.selectat' and put in text, like a mount.

Ex: 10 + 20 + 15 = 45

http://jsfiddle.net/wdLaR/

HTML:

     <div class="div">
          <ul class="lista-analize">
                    <li class="a" data-pret="10">Hemoleucogramă completă <span class="pret">10 lei</span></li>
                    <li class="a" data-pret="15">Numărare reticulocite <span class="pret">15 lei</span></li>
                    <li class="a" data-pret="20">VSH <span class="pret">20 lei</span></li>
                    <li class="a" data-pret="10">INR (International Normalised Ratio) <span class="pret">10 lei</span></li>
                    <li class="a" data-pret="15">Determinare grup sanguin ABO <span class="pret">15 lei</span></li>
                    <li class="a" data-pret="25">Determinare grup sanguin RH <span class="pret">25 lei</span></li>
                    <li class="a" data-pret="35">Colinesteraza <span class="pret">35 lei</span></li>
                    <li class="a" data-pret="5">Proteine serice totale <span class="pret">5 lei</span></li>
                    <li class="a" data-pret="15">Hemoglobina glicozilată (HbA1C) <span class="pret">15 lei</span></li>
                    <li class="a" data-pret="20">Factor rheumatoid <span class="pret">20 lei</span></li>
                </ul>

                <span id="total"></span>

Jquery

$(document).ready(function(){
$('.content-stanga').on('click', 'li.a', function(){
   $(this).toggleClass("selectat", 200);

   var sume = 0;

while (($(this).hasClass("selectat")) && (sume === 0)) { 
  var sume = +$(this).data("pret");
}

$('#total').text(sume);

});
});

preguntado el 24 de mayo de 14 a las 16:05

= +? Should not it be +=? -

1 Respuestas

Puedes usar each() to sum the data values where the element has that class. Also, you do not want to use the var keyword when setting the value of sume within the loop, and the condition to check if sume == 0 is counter-productive with getting the total of the selected elements, as it will only add the first item. Finally, to increment a variable with a value, it's +=no, = +.

Prueba esto:

$('.content-stanga').on('click', 'li.a', function(e) { 
    e.preventDefault();
    $(this).toggleClass("selectat");
    var sume = 0;
    $('.content-stanga li.a.selectat').each(function() {
        sume += $(this).data('pret');
    });
    $('#total').text(sume);
});

Violín de ejemplo

contestado el 24 de mayo de 14 a las 16:05

Oh thanks for that, it work very good. But you cand explain me about (e) after function, e.preventeDefault(); ? I`m work with basics.. - user3671971

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.