1

I have a problem with jQuery, i have tried this with both jQuery and JavaScript and the issue is the same. So, this issue i have is that im trying to get a value from a selectinput and a hidden input and calculate those values and print the calculated value to a div. But instead of calculating the value it prints both values. For example, if i choose option1 in selectinput that has value1 and my hidden input has value 7 it prints 71 instead of 8. I have been looking and different ways to calculate with JavaScript and jQuery but i dont find any solution to my problem. Im sure this has been posted before but i have no idea what to search for so i dont have any idea how to find the answer im looking for. So i apologize if this question has been asked already.

function test(str) {
  var result = $("[type='hidden']").val()+str;
  $('.output').html(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select onchange="test(this.value)">
  <option value="" selected hidden></option>
  <option value="1">Option1</option>
  <option value="2">Option2</option>
  <option value="3">Option3</option>
  <option value="4">Option4</option>
  <option value="5">Option5</option>
</select>
<input type="hidden" value="7">
<div class="output"></div>
Tim Levinsson
  • 597
  • 2
  • 7
  • 20
  • Because `"2" + "2" = "22"` while `2 + 2 = 4` – epascarello Nov 27 '18 at 14:50
  • 1
    I'm sure there's a duplicate of this, but: if you use `+` and either side is a string, you get a string. `.val()` returns a string (and I assume `str` is a string) - so will concatenate the values, not apply mathematics to them. Convert to integers first (`parseInt(str, 10)` or `(str*1)`). `var result = ($("[type='hidden']").val()*1)+(str*1);` – freedomn-m Nov 27 '18 at 14:50

1 Answers1

2

Just cast the value to a int like so:

function test(str) {
  var result = parseInt($("[type='hidden']").val()) + parseInt(str);
  $('.output').html(result);
}
Thomas
  • 2,431
  • 17
  • 22
  • 2
    Just to add to this good answer, you could also use parseFloat() depending on what your data needs. – HyperTextCoffeePot Nov 27 '18 at 14:54
  • 1
    Thank you, This solved my problem. For some reason i need to wait 6 minutes to mark this answer as the solution to my problem. But i will mark this as soon as possible – Tim Levinsson Nov 27 '18 at 14:57