2

Hello (yet again) a question about javascript, this one has to be an easy one but I just can't see what I did wrong, I think something really stupid:

I have a textbox and a button. When i click the button the value wil be passed to a variable called activiteitn. Code:

    activiteitn = $("#m2activiteitn").val();

It gets the value, so when I filled in the number 1, activiteitn = 1. After that I have a switch that looks like this:

        switch(activiteitn) {
        case  1: activiteitn = 1.2;
        break;
        case  2: activiteitn = 1.375;
        break;
        case  3: activiteitn = 1.55;
        break;
        case  4: activiteitn = 1.725;
        break;
        case  5: activiteitn = 1.9;
        break;
        default: alert("hoi");
        break;
        }

The problem is that even if I fill in the number 1, it jumps to the default case, causing it to alert. If I place a alert at case 1 that alert does not show up. The first thing that came in my mind was that the activiteitn was not 1, so right after the switch I placed another alert:

        alert (activiteitn);

Now, first what happends is I get the alert "hoi", then I get the second alert of activiteitn that says: 1. So after that I thought, "Maybe its a string", so I changed the cases to strings like: case "1" & case ("1") but that did not work either. The problem, it always goes to the default case and I can not figure out why that is, I hope someone sees what I did wrong and can help me out.

Niek Jonkman
  • 477
  • 4
  • 11
  • 23

2 Answers2

5

.val() returns a string, not a number. So after the line:

activiteitn = $("#m2activiteitn").val();

the variable activiteitn actually equals "1", not 1. Since case...switch uses strict equality, your test will always fail.

To fix, simply change the above line to:

activiteitn = +$("#m2activiteitn").val(); // convert to a number

or

activiteitn = parseInt($("#m2activiteitn").val(),10); // convert to an integer

or

activiteitn = parseFloat($("#m2activiteitn").val()); // convert to a float
Community
  • 1
  • 1
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
1

Use parseInt(activiteitn, 10); to turn your String into an Integer. Switch-case statements in Javascript don't play nicely with Strings half the time.

Bucket
  • 7,415
  • 9
  • 35
  • 45
  • 5
    [Always use a radix with parseInt](http://stackoverflow.com/questions/5600366/why-does-the-radix-for-javascripts-parseint-default-to-8) – Blazemonger May 29 '13 at 13:23