0

This is my code:

 $(document).ready(function () {
        $("#afiseaza_subtotal").click(function(){
            var i = 0; var list = []; 
            $(".name1").each(function(){
                list[i] =  $(this).val();
                i++;
            });
            var uniqueNames = [];
            $.each(list, function(i, el){
                if (el !=""){
                    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
                }
            });
            var html = "";
            if (uniqueNames.length > 0){
                $.each(uniqueNames, function(i, value){
                    var sum = 0;
                    if ($(".name1").attr("value") == value ){
                       // sum = parseFloat($(this).parent(".prod-persoana1").prev(".prod-pret1").find(".price").text());
                    }
                    //

                    html += "<p>Subtotal "+value+"-"+ sum +" lei </p>";

                });
                // initial_html = $(".subtotal").html();
                $(".subtotal").append(html);
            }else{
                alert("dasdasd");
            }
        });

    });

In the array uniqueNames i have all of the DISTINCT inputs value. I also another item where it is the sum. I want to get all of the sum value from the same input. See the example below:

 12$    Name1
 13.4$  Name2
 14$    Name1
 14$    Name3

the result will be a subtotal, which will look like this:

26$    Name1
13.4$  Name2
14$    Name3

As I said in the array uniuqNames I got the unique Names. Now I need to get the sum . How do I get the sum ?

This is the html code:

<div class="prod-pret1">
    <span class="price bolder">6.8 </span> Lei
</div>
<div class="prod-persoana1">
    <input name="nume1" type="text" id="nume1" class ="name1" value="" placeholder="Nume">
</div>
<div class="prod-pret1">
    <span class="price bolder">6.8 </span> Lei
</div>
<div class="prod-persoana1">
    <input name="nume2" type="text" id="nume2" class ="name1" value="" placeholder="Nume">
</div>
.....
1
  • If I m not making myself clear, please ask :) Commented Dec 12, 2014 at 11:01

5 Answers 5

1

You've overcomplicated:

$('button').on('click',function(){
    var subtotal = {};
    $('input').each(function(){
       var $this = $(this);
        var cls = this.className;
        if(subtotal[cls] === undefined){
             subtotal[cls] = parseFloat($this.val());   
        }
        else{
             subtotal[cls] += parseFloat($this.val());   
        }
    });
    
    console.log(subtotal);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="nume1" type="text" id="nume1" class ="name1" value="12" placeholder="Nume">
<input name="nume2" type="text" id="nume2" class ="name2" value="13.4" placeholder="Nume">
<input name="nume2" type="text" id="nume2" class ="name1" value="14" placeholder="Nume">
<input name="nume3" type="text" id="nume3" class ="name3" value="14" placeholder="Nume">    
<button>Calculate subtotal</button>

Output (to console):

Object { name1=26, name2=13.4, name3=14}

Sign up to request clarification or add additional context in comments.

2 Comments

Agreed.. thats way to overcomlicated html structure, as I already advised him to adopt more of a readable class structure.
@edduvs - it wasnt the html structure i meant was overcomplicated - html is html, its structured how it needs to be. What was overcomplicated was the javascript and the way it dealt with getting a unique set then trying to query it
0

Well, this could easily be accomplished when you're pushing the unique name into the array.

 if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);

Should actually run another block of code similar to this :

var subTotals = {};
if($.inArray(el, uniqueNames) === -1) {

   $.each ( ELEMENTS_WITH_PRICES_FOR_CURRENT_NAME , function () {
      subTotals[el] += parseFloat($(this).parent(".prod-persoana"+el).prev(".prod-pret"+ el).find(".price").text())
   });

   uniqueNames.push(el);

}

subTotals[ el ] is being incremented with your "formula" of getting the price which is really wierd. You should really adopt other HTML structure. I can't really understand it. But the idea is similar.

Comments

0
$(document).ready(function () {
    $("#afiseaza_subtotal").click(function(){
        //Contains all the classes of the inputs and sum of their values
        var uniquenames = [];
        $('input[type="text"]').each(function(){
             /*First time seeing this class, set value and key in array.*/
             if(uniquenames[$(this).class()] === "undefined")
             {
                 uniquenames[$(this).class()] = parseInt($(this).val());
             }
             else
             {
                 /*Add value in array*/
                 uniquenames[$(this).class()] += parseInt($(this).val());
             }
        });
        /*Use the uniquenames array in anyway you want :) The key = class; value = sum*/
    });
}); 

Comments

0

This version works for me:

$(document).ready(function () {
        $("#afiseaza_subtotal").click(function(){
            $(".new_subtotal").each(function(){
                $(this).remove();
            });
            var i = 0; var list = []; 
            $(".name1").each(function(){
                list[i] =  $(this).val();
                i++;
            });
            var uniqueNames = [];
            $.each(list, function(i, el){
                if (el !=""){
                    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
                }
            });
            var html = "";
            if (uniqueNames.length > 0){
                $.each(uniqueNames, function(i, value){
                    var sum = 0;
                    $(".prod-pret1").each(function(){
                            initial_sum = parseFloat($(this).find(".price").text());

                            compare_value = $(this).next(".prod-persoana1").find(".name1").attr("value");
                            if (compare_value == value){
                                sum = sum + initial_sum;
                            }
                    });
                    html += "<p class='new_subtotal'>Subtotal "+value+"-"+ sum +" lei </p>";

                });
                // initial_html = $(".subtotal").html();
                $(".subtotal").append(html);
            }else{
                alert("dasdasd");
            }
        });

    });

Comments

0

Try this

     $(document).ready(function () {
        $("#add").click(function () {
            var data = {};
            $("input[type='text']").each(function () {
                if (data[this.className] == undefined) {
                    data[this.className] = $("." + this.className).sum();
                }
            });
            $("#result").html(JSON.stringify(data, null, 4));
        });
    });

    (function ($) {
        $.fn.sum = function () {
            var s = 0.00;
            $(this).each(function () {
                s += Number($(this).val());
            });
            return s;
        };
    })(jQuery);

HTML:

<div>
    <input type="text" id="txt1" class="name1" value="14" />
    <input type="text" id="txt2" class="name1" value="14" />
    <input type="text" id="txt3" class="name2" value="14" />
    <input type="text" id="txt4" class="name3" value="14" />
</div>
<input type="submit" id="add" value="Calculate" />
<div id="result">
</div>

Output:

{ "name1": 28, "name2": 14, "name3": 14 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.