2

This is my drop down menu ---

<select name="category" id="category" onChange="showDiv(this.value);" >
    <option value="">Select This</option>
    <option value="1">Nokia</option>
    <option value="2">Samsung</option>
    <option value="3">BlackBerry</option>
    <option value="4">Spice</option>
    <option value="5">HTC</option>
    </select>

This is my span class where i want to show the data on the basis of selection

<span class="catlink"> </span>

My JS Function (although the function is working fine when i am doing it through if conditions)

function showDiv(discselect) {
    switch(discselect) {
    case 1:
        document.getElementsByClassName("catlink")[0].innerHTML = '<a href="nokia.txt">Click To Download</a>';
        break;
    case 2:
        document.getElementsByClassName("catlink")[0].innerHTML = '<a href="samsung.txt">Click To Download</a>';
        break;
    case 3:
        document.getElementsByClassName("catlink")[0].innerHTML = '<a href="blackberry.txt">Click To Download</a>';
        break;
    default:
        alert(discselect);
        document.getElementsByClassName("catlink")[0].innerHTML = 'aaaa';
    }
}

Now on running the code each time the default case gets executed whereas 1,2,3 is still alerting, let me know what i am doing wrong and whr my logic lags??

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
swapnesh
  • 26,318
  • 22
  • 94
  • 126
  • please _don't repeat yourself_ ! Just evaluate `document.getElementsByClassName('catlink')[0]` _once_ – Alnitak Jun 01 '12 at 09:56
  • 1
    [`switch...case` uses strict comparison](http://stackoverflow.com/questions/6989902/is-it-safe-to-assume-strict-comparison-in-a-javascript-switch-statement?lq=1); you're comparing a string to an integer. – Blazemonger May 29 '13 at 13:29

3 Answers3

5

Your discselect is coming across as a string..so you need to change your case to:

switch ( discselect ){
  case '1':
    break;
  case '2':
    break;
  case '3':
    break;
  default:
    alert(discselect);
  }
}
ltiong_sh
  • 3,186
  • 25
  • 28
3

Javascript's case tests are strict: if discselect is a string and not a number, your code will always take the default branch.

You can convert discselect to a number in your switch statement:

switch (+discselect) {
    // ...
}

Or use strings in your case tests:

switch (discselect) {
    case "1":
        // ...
        break;

    // ...
}
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
0
onChange="showDiv(this.value);"

should be

onchange="showDiv(this.options[this.selectedIndex].value)"

EDIT: and

switch (discselect) {

should be

switch (+discselect) {
Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
  • 2
    umm, no, they're (almost) equivalent. If anything the latter is more error prone because `selectedIndex` can be -1 – Alnitak Jun 01 '12 at 09:54
  • @Alnitak you're right. It solve nothing. but `switch(+discselect)` yes. I edit for complete answer (and +1ing to Frederic) – Luca Rainone Jun 01 '12 at 10:01