-1

How to distinguish the jquery operator which is used to concatenate elements, from the + sign which is used to add elements? Here, I try to add the values of two inputs. In my code, more complex, the result is the same, it does not add but concatenates the elements..

Here is my code, I can"t see what's wrong here

a=$('#a').val()+'px';
b=$('#b').val()+'px';

c=(a+b);


  $('#result').html(c);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js" integrity="sha512-pumBsjNRGGqkPzKHndZMaAG+bir374sORyzM3uulLV14lN5LyykqNk8eEeUlUkB3U0M4FApyaHraT65ihJhDpQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
 
<input id="a" type="number" value="10">

<input id="b" type="number" value="10">


<output id="result"></output>
blogob
  • 490
  • 5
  • 19
  • You're concatenating concatenated strings. You need `c=(parseInt(a)+parseInt(b));` – Aksen P Apr 09 '23 at 10:07
  • And don't concate the inputs with `'px'` before adding them – Cid Apr 09 '23 at 10:23
  • What exactly did you think "123px" plus "456px" would be? It's not a number because it has "px". Did you want to add the 123+456 *then* add the px? – freedomn-m Apr 10 '23 at 09:43

1 Answers1

2
a=$('#a').val(); b=$('#b').val(); 
c= parseInt(a)+parseInt(b)+'px';    
$('#result').html(c);

use parseInt to plus

Lalit Kumar
  • 256
  • 2
  • 14