I had this passage, working and happy. Note that I'm numberizing (does it count as casting in JS?) the value being added.

var total = 0;
$.each($("input[blopp]:checked"), function(index, value) {
  $("#Service")[0].value += +value.attributes["blopp"].value;
  total += +value.attributes["blopp"].value;
$("#Service")[0].value = total;

The Service control is a hidden field generated by Razor, which based on the model provided to the ASP.NET view is of type int. (I suspect it's of no relevance because once on the page, we only have HTML, JS and CSS but I've been mistaken before.)

Then I started to do that thing called thinking and it wasn't very successful. The number of line got smaller, which increased readability. However, the result now isn't a sum but a concatenation of the values, because the holding variable is a string.

$.each($("input[blopp]:checked"), function(index, value) {
  $("#Service")[0].value += +value.attributes["blopp"].value;

My question is a simple way to type (not to type as in punch on the keys but as in to enforce a certain type to) the receiving variable so it knows that it's a number?

The question isn't about:

  1. how the conversion to string occurs (it's already perfectly obvious),
  2. how to numberize the receiver before the operation, i.e. a = (+a) + (+b) (a += b syntax preferred),
  3. how to add a prototype to strings (it's simpler to go back to the original version),
  4. how much gain there's to readability nor premature optimization (academic curiosity only),
  5. how to avoid polluting the global scope (there's already IIFE around it).

Related posts

Recent Viewed