3

I made a fiddle! https://jsfiddle.net/ajc100/vrzme0st/

I'm trying to make an insurance calculator (using fake numbers). It consists of a form with radio buttons and dropdowns and the value of each radio button or dropdown is a number. I used alert to show that the correct number is being applied based on what the user chooses. What I need to do now is add the numbers together to get a total. The problem I'm having is that I'm not sure how to convert the variable's value, which is a number, to an integer so that Javascript understands it as a number and can add it. This is my code. (Jquery actually). As you can see, I've tried a few different things to get the value of the variable to convert to a number but nothing seems to work. Any help is greatly appreciated.

 <ul>
  <li><form id="sex"><legend>Sex</legend> <fieldset>
  <input type="radio" name="sex" value="20" id="Female" class="firstInput css-checkbox" />
  <label class="css-label" for="Female">Female</label>
     <input type="radio" name="sex" value="30" id="Male" class="css-checkbox" />
     <label class="css-label" for="Male">Male</label></fieldset>
      </form>
      </li>

  <li>
  <form id="age"><legend>Age</legend><fieldset>
    <input type="radio" id="sixteen" name="age" value="40" class="firstInput css-checkbox" />
    <label class="css-label" for="sixteen">16-25</label>
      <input id="twentysix" type="radio" name="age" value="30" class="css-checkbox" />
      <label class="css-label" for="twentysix">26-34</label>
        <input type="radio" id="thirtyfive" name="age" value="20" class="css-checkbox"  />
        <label class="css-label" for="thirtyfive">35-50</label>
          <input type="radio" name="age" id="fifty" value="15" class="css-checkbox" />
          <label class="css-label" for="fifty">50+</label></fieldset>
          </form>
          </li>

  <li>Car Color
    <select name="color" id="car">
      <option value="80">red</option>
      <option value="50">silver</option>
      <option value="50">black</option>
      <option value="30">white</option>
      <option value="50">other</option>
    </select>
  </li>

  <li>Car Year
    <select name="year" id="year">
      <option value="60">2015+</option>
      <option value="40">2000 - 2015</option>
      <option value="60">1999 or before </option>

    </select></li>

    <li>Citations in past year
      <select name="citations" id="citations">
        <option value="20">1</option>
        <option value="30">2</option>
        <option value="40">3+</option>

      </select>

    </li>
  </ul>

  <hr>
  <div class="total">Total</div>

</div>

<script>

  $('#sex input').on('change', function() {
   var sex = ($('input[name="sex"]:checked', '#sex').val()); 
   parseInt(sex);
   alert(sex);
 });

  $('#age input').on('change', function() {
   var age = ($('input[name="age"]:checked', '#age').val()); 
   number(age);
   alert(age);
 });

  $('#car').on('change', function() {
   var car = parseInt($('#car').val(),10); 
   alert(car);
 });

  $('#year').on('change', function() {
   var year = +($('#year').val()); 
   alert(year);
 });

  $('#citations').on('change', function() {
   var citations = ($('#citations').val()); 
   parseInt(citations);
   alert(citations);
 });

I tried this and it's still not working. I can't seem to add the variables together even after switching them to numbers:

<script>
$(document).ready(function() {

  $('#sex input').on('change', function() {
    sex = ($('input[name="sex"]:checked', '#sex').val());
    sex = +sex;
  });

  $('#age input').on('change', function() {
    age = ($('input[name="age"]:checked', '#age').val());
    age = +age;
  });

  $('#car').on('change', function() {
    car = ($('#car').val());
    car = +car;
  });

  $('#year').on('change', function() {
    year = ($('#year').val());
    year = +year;
  });

  $('#citations').on('change', function() {
    citations = ($('#citations').val());
    citations = +citations;
  });

  var total = sex + age + car + year + citations;
  $(".total").text("Total: " + total);

});

</script>
Barmar
  • 741,623
  • 53
  • 500
  • 612
AJMC
  • 73
  • 6
  • Possible duplicate of [How do I convert a string into an integer in JavaScript?](http://stackoverflow.com/questions/1133770/how-do-i-convert-a-string-into-an-integer-in-javascript) – Bill the Lizard May 18 '16 at 22:50
  • @BilltheLizard He already knows about the `parseInt` function. His confusion is about how to use functions in general. – Barmar May 18 '16 at 22:52
  • Where are you trying to add values? – trincot May 18 '16 at 22:53
  • I'm trying to add the values to come up with a total cost for car insurance based on the answers that someone selects. – AJMC May 20 '16 at 19:15

3 Answers3

2

parseInt and Number are functions that return the numerical value. They don't change the argument.

So write:

sex = parseInt(sex);

or:

age = number(age);

But much simpler and most efficient is the unitary plus:

age = +age;

You don't show code where you add variable values, but after you have converted them like this you can add them as expected.

Order of events and automatically created variables

The problem with your code is that you calculate the total when the page loads, at a time when none of the variables is set by the click handlers (sex, age, ...). Instead they are set by the rule that browsers automatically create a variable for each element that has an "id" attribute, with that name. But those variables represent DOM elements, and so your total cannot work. Also that total never gets updated when the user changes a selection.

Instead I suggest using this code:

function refreshTotal() {
    var sex = +$('input[name="sex"]:checked', '#sex').val();
    var age = +$('input[name="age"]:checked', '#age').val();
    var car = +$('#car').val();
    var year = +$('#year').val();
    var citations = +$('#citations').val();
    var total = sex + age + car + year + citations;
    $(".total").text("Total: " + total);
}

// Create one handler for all input/select changes:
$('input,select').on('change', refreshTotal);

// Also at page load, calculate the total 
$(refreshTotal);
trincot
  • 317,000
  • 35
  • 244
  • 286
  • I tried this and I'm still not having any luck. I'll add to my original question to show you what I did. – AJMC May 20 '16 at 19:15
  • That is because you have some other conceptual problems. See the addition to my answer. I added some code that works. – trincot May 20 '16 at 20:55
  • Ok, so far so good, but there is one more thing. When we refresh it when the page loads, it shows NaN as the total. I'd rather not have that there, so I removed the call to the function when the page loads which took care of that, but then when you make the first selection of male or female, it says NaN and only changes to a number after another selection has been made. Thoughts? – AJMC May 21 '16 at 21:52
  • Either put the code with the call `refreshTotal()` just before the end of the `body` tag, or pass `refreshTotal` (without brackets) to `$(...);`, so it gets only executed when DOM is ready. I updated it like that in my answer. – trincot May 22 '16 at 09:05
  • Actually, after I asked that last question, I realized that it wasn't working if I answered the questions out of order either, and I think that was because it was trying to get a value for variables where no selection had been made yet, so I added some code that checked if each one was NaN and if it was, changed it to 0 and that took care of it. Thanks for all your help!!! – AJMC May 23 '16 at 15:29
2

When you call a function, you generally need to assign the result somewhere; the function can't change the value of the variable itself (functions that take objects as arguments can modify the contents of the objects, but that's not the same as modifying the variable that was used in the call). When you write

parseInt(sex);

it calls the function, but doesn't do anything with the result. You need to do:

sex = parseInt(sex, 10);

You should also always specify the radix when calling parseInt; the specification doesn't require it to be decimal by default, and some old browsers have a different default.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I don't understand why this was downvoted. You got my vote. – trincot May 18 '16 at 22:54
  • @trincot Someone downvoted all the answers. I suspect it was the dupe-voter, who maybe thinks this is too trivial to bother answering. – Barmar May 18 '16 at 22:55
  • Ah, yes, that might be it. – trincot May 18 '16 at 22:56
  • I tried this as well as the suggestion of the answerer below this one. I still can't add the variable values together. Does it have something to do with the way I have the code set up? Something to do with scope perhaps? – AJMC May 20 '16 at 19:18
  • You're calculating the total when the page is first loaded, but you never update it after the user edits the inputs. – Barmar May 20 '16 at 19:33
1

You can cast string into int by

var a = "10";
var b = parseInt(a); 

Hope it helps!

eracube
  • 2,484
  • 2
  • 15
  • 18