web-dev-qa-db-fra.com

Comment forcer l'addition au lieu de la concaténation en javascript

J'essaie d'ajouter tout le contenu en calories dans mon javascript comme ceci:

$(function() {
    var data = [];

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
            var currentId = $(ui.draggable).attr('id');
            var total = 0;
            data.Push($(ui.draggable).attr('id'));

            if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
            }
            if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
            }
            if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
            }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
        myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
        myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total = parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').append(total);
        }
    });
    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

Au lieu d'ajouter les variables, elles sont concaténées. J'ai essayé d'utiliser parseInt, parseFloat et Number, mais je n'obtiens toujours qu'une concaténation et pas une addition. Veuillez regarder la source de vue sur http://maureenmoore.com/momp_112412/121912_800.html

38
Maureen Moore

Votre code concatène trois chaînes, puis convertit le résultat en un nombre.

Vous devez convertir chaque variable en un nombre en appelant parseFloat() autour de chacune d'elles.

total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);
67
SLaks

Devrait également pouvoir faire ceci:

total += eval(myInt1) + eval(myInt2) + eval(myInt3);

Cela m'a aidé dans une situation différente, mais similaire.

7
vapcguy

L'instruction suivante ajoute la valeur à l'élément avec l'id de response

$('#response').append(total);

Cela donne l’impression que vous concaténez les chaînes, mais vous ne les ajoutez pas, vous les ajoutez à l’élément.

changer cela en 

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

Vous devez modifier l'événement drop pour qu'il remplace la valeur de l'élément par le total. Vous devez également garder trace du total. Je suggère quelque chose comme ce qui suit:

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');
        data.Push($(ui.draggable).attr('id'));

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        }
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        }
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total += parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').text(total);
        }
    });

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

J'ai déplacé l'instruction var total = 0; en dehors de l'événement drop et modifié la déclaration d'affectation de cette

total = parseFloat(myInt1 + myInt2 + myInt3);

pour ça

total += parseFloat(myInt1 + myInt2 + myInt3);

Voici un exemple de travail http://jsfiddle.net/axrwkr/RCzGn/

1
user1873471