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);
});
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.
To avoid unexpected string concatenation while concatenating strings, multiple strings, and numbers, use backticks.
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.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With