SpaceNinja
SpaceNinja

Reputation: 512

Default in a Javascript Switch Statement works with just one case, but not two?

When I wrote this code with just one case, the alert fired just fine when I clicked a case other than 1 or 2. When I added more than one, the default no longer fires the alert when I click a case other then 1 or 2. What gives? Thank you in advance.

function displayLoc(locNum) {

    switch (locNum) {

        case 1:
            $('#loc-name').html('Google');
            $('#loc-web').attr('href','http://www.google.com');
          break;

        case 2:
            $('#loc-name').html('StackOverflow');
            $('#loc-web').attr('href','http://www.stackoverflow.com');
          break;

        default:
            alert('Location coming soon!');
    }
}

Upvotes: 0

Views: 83

Answers (1)

plalx
plalx

Reputation: 43728

Your code seems just fine. It must be something else.

However may I suggest you a different solution?

var locations = [
    ['Google', 'http://www.google.com'],
    ['StackOverflow', 'http://www.stackoverflow.com']
];

function displayLoc(locNum) {
    var loc = locations[locNum];

    if (!loc) {
        alert('Location coming soon!');
        return;
    }

    $('#loc-name').html(loc[0]);
    $('#loc-web').attr('href', loc[1]);
}

Upvotes: 1

Related Questions