Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an addition instead of a concatenation

Tags:

jquery

I have an input button. I created for this input an attribute called "multiplicateur" which has the value of 1. When the button is clicked I have a .click() triggered. The function is suppose to get the value of the attribute and add 1 to it. So my output should be 2. Instead the output is 11. It seems the system makes a concatenation instead of an addition.

My HTML:

<input id="envoyer" type="submit" multiplicateur=1>

My JS:

$('#envoyer').click(function() {
    var ajaxData = $(this).attr('multiplicateur');
    alert(ajaxData + 1);
});
like image 649
Marc Avatar asked Jan 31 '12 14:01

Marc


People also ask

Why are my numbers concatenating instead of adding?

The + sign concatenates because you haven't used parseInt(). The values from the textbox are string values, therefore you need to use parseInt() to parse the value.

How do you avoid concatenation?

To avoid unexpected string concatenation while concatenating strings, multiple strings, and numbers, use backticks.

Is concatenation the same as addition?

Both addition and concatenation use the same + operator, but they are not same. Concatenation is used to concatenate i.e. add strings, whereas simple addition adds numbers.

How do you do addition in JavaScript?

Basic JavaScript Addition Add numbers in JavaScript by placing a plus sign between them. You can also use the following syntax to perform addition: var x+=y; The "+=" operator tells JavaScript to add the variable on the right side of the operator to the variable on the left.


1 Answers

ajaxData is a string. Thus, you need to parse it to an integer...

 $('#envoyer').click(function() {
    const ajaxData = $(this).attr('multiplicateur');

    /* parse string to integer */
    alert(parseInt(ajaxData) + 1);

});
like image 156
Alex Avatar answered Oct 14 '22 15:10

Alex