[jquery] How to force addition instead of concatenation in javascript

I'm trying to add all of the calorie contents in my javascript like this:

$(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);
        });
    });
});

Instead of adding the variables they get concatenated. I've tried using parseInt, parseFloat, and Number but I still just get concatenation and not addition. Please look at the view source at http://maureenmoore.com/momp_112412/121912_800.html

This question is related to jquery scope concatenation addition

The answer is


The following statement appends the value to the element with the id of response

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

This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to

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

You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(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);
        });
    });
});

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

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

Here is a working example http://jsfiddle.net/axrwkr/RCzGn/


Your code concatenates three strings, then converts the result to a number.

You need to convert each variable to a number by calling parseFloat() around each one.

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

Should also be able to do this:

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

This helped me in a different, but similar, situation.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to scope

Angular 2 - Using 'this' inside setTimeout Why Is `Export Default Const` invalid? How do I access previous promise results in a .then() chain? Problems with local variable scope. How to solve it? Why is it OK to return a 'vector' from a function? Uncaught TypeError: Cannot read property 'length' of undefined Setting dynamic scope variables in AngularJs - scope.<some_string> How to remove elements/nodes from angular.js array Limiting number of displayed results when using ngRepeat A variable modified inside a while loop is not remembered

Examples related to concatenation

Pandas Merging 101 What does ${} (dollar sign and curly braces) mean in a string in Javascript? Concatenate two NumPy arrays vertically Import multiple csv files into pandas and concatenate into one DataFrame How to concatenate columns in a Postgres SELECT? Concatenate string with field value in MySQL Most efficient way to concatenate strings in JavaScript? How to force a line break on a Javascript concatenated string? How to concatenate two IEnumerable<T> into a new IEnumerable<T>? How to concat two ArrayLists?

Examples related to addition

How to find difference between two columns data? How to force addition instead of concatenation in javascript How to add an integer to each element in a list? How to force JS to do math instead of putting two strings together Time calculation in php (add 10 hours)?