开发者

jQuery - Retrieve values from HTML elements and return their sum

I got a form with several checkbox's where the 开发者_开发技巧user can choose multiple values, like so:

<div>
    <input id="myinput1" type="checkbox" value="choice_id_1" />
    <label for="myinput1">5</label>
</div>
<div>
    <input id="myinput2" type="checkbox" value="choice_id_2" />
    <label for="myinput2">10</label>
</div>
<div>
    <input id="myinput3" type="checkbox" value="choice_id_3" />
    <label for="myinput3">10</label>
</div>

I need to get the values from each :selected checkbox label and return their total sum (ie: total = 25).

So far I have been trying to get the strings from the labels with the .text() method, make an array with the results, converting them to int with parseFloat() and sum the array elements... obviosly with no success.

This is what i got (for sure not the best approach so I'm open to diferent solutions):

function totalSum() {
    var prices = $("input:checkbox:checked").siblings("label").text();
    var myArray = $.makeArray(prices);

    var total = 0;
    for(var i = 0; i < myArray.length; i++){
        var thisVal = parseFloat(myArray[i]);
        if(!isNaN(thisVal)){
            total += thisVal;
        }
    };

    $(".mydiv").text(total);
};

totalSum();
$("input:checkbox").change(totalSum);


the solution is as follow, you can go here to try out the demo

<form id="sum" action="#">
<div><input id="myinput1" type="checkbox" value="choice_id_1" />
<label for="myinput1">5</label></div>
<div><input id="myinput2" type="checkbox" value="choice_id_2" />
<label for="myinput2">10</label></div>
<div><input id="myinput3" type="checkbox" value="choice_id_3" />
<label for="myinput3">10</label></div>
<input class="submit" type="submit" value="Submit" />
<div id="result"></div>
</form>

<script type="text/javascript">
 jQuery(document).ready(function() {
   jQuery('.submit').click(function(event){
     var sum = 0;
     jQuery('form#sum').find(':checkbox').each(function() {
      if (jQuery(this).is(':checked')) {
       var labelVal = parseInt(jQuery(this).next().text());
       sum +=labelVal;
      }
     });
     jQuery('#result').text('The total is ' + sum);
   });
 });
</script>


Well for one thing change the value part of each checkbox to the same as the value of the label (if you can't do that, you can utilize the name attr of the input as shown below):

<div>
    <input id="myinput2" type="checkbox" value="choice_2" name="10"/>
    <label for="myinput2">10</label>
</div>

and then the JS can be like this:

function totalSum() {
    var prices = $("input:checkbox:checked");

    var total = 0;

    $.each(prices, function(index, obj){
        total += parseFloat($(obj).attr('name'));
    })


    $(".mydiv").text(total);
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜