Pergunta

This is my code, here there are 6 checkboxes and it call 6 times and each time it make sum of both values, i am passing value like 10,10 than it should be a 20 but it returns 120, How can I solve this problem?

jQuery('.pricefield input').each( function() {
  var checkedValues = jQuery('input:checkbox:checked').map(function() {
    str=this.value;
    source_str = str.substr(str.indexOf("#"));
    keywords = source_str.split (/[\D,]+/);
    val1=keywords[1];
    val2=keywords[2];
    sum+=parseInt(val1, 10)+parseInt(val2, 10);
    alert(sum);
    pricefield_both(sum);
  }).get();
});
Foi útil?

Solução

You are not looking at the correct indexes and you need one more position after the #

Live Demo

$(function() {
  $('.pricefield input').on("click",function () {
    var sum=0;
    $('input:checkbox:checked').each(function () {
        var str=$(this).val().split("#")[1].split(",");
        sum += (parseInt(str[0], 10) + parseInt(str[1], 10));
    });
    pricefield_both(sum); // assuming that function works
  });
});    

Outras dicas

keywords = source_str.split (/[\D,]+/);
val1=keywords[1];
val2=keywords[2];
sum+=parseInt(val1, 10)+parseInt(val2, 10);

this code is not good!

try something like bellow!

keywords = source_str.split(/[\D,]+/);
val1 = +keywords[1];
val2 = +keywords[2];
sum += val1 + val2;

and I suggest you define the variables first so the local variable will not become globally accessble!

var str, source_str, keywords, val1, val2, sum; 

the result is bellow:

var str, source_str, keywords, val1, val2, sum = 0;
jQuery('.pricefield input').each( function() {
  var checkedValues = jQuery('input:checkbox:checked').map(function() {
    str=this.value;
    source_str = str.substr(str.indexOf("#"));
    keywords = source_str.split (/[\D,]+/);
    val1 = +keywords[1];
    val2 = +keywords[2];
    sum += val1 + val2;
    alert(sum);
    pricefield_both(sum);
  }).get();
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top