5

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);
});
JJJ
  • 32,902
  • 20
  • 89
  • 102
Marc
  • 9,217
  • 21
  • 67
  • 90

4 Answers4

21

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);

});
Alex
  • 34,899
  • 5
  • 77
  • 90
  • You code works but when i test it in JS Fiddle it returns an error (Missing radix parameter). Do you know why? – Marc Jan 31 '12 at 15:04
  • @user1162116 It's intriguing your to receiving that error as the second parameter to `parseInt` is optional. Try passing 10 - `parseInt(ajaxData, 10)` – Alex Jan 31 '12 at 15:26
  • No error know! Great. What does the second parameter represent? – Marc Jan 31 '12 at 15:34
  • @user1162116 the second parameter is the ***radix*** or ***base*** (number of unique digits). I assumed you wanted the common *base 10* – Alex Jan 31 '12 at 17:25
3

You have to parse it first:

    parseInt(ajaxData)+1;
Sören Titze
  • 985
  • 1
  • 12
  • 31
1

In order to add value with decimal point, please use parseFloat(ajaxData)

alert(parseFloat(ajaxData) + 1);

0

For substracting

function removeFromQtt(){
             $("qty").value = parseInt($("qty").value)-1;
 }

For addition

function add(){
             $("qty").value = parseInt($("qty").value)+1;
 }
Ahmed Adewale
  • 2,943
  • 23
  • 19