David
David

Reputation: 27

Trouble with a switch on a string in javascript

function listUsers(profil) {
    alert("type "+typeof(profil));
    switch (profil.toUpperCase()) {
        case "DGA":
            document.getElementById("id_importeur").innerHTML = "<?php echo $html_DGA; ?>";
            break;
        case "INDUSTRIEL":
            document.getElementById("id_importeur").innerHTML = "<?php echo $html_indus; ?>";
            break;
        default:
            alert("<?php echo plugin_lang_get("profil_err_users"); ?>");
    }
}

For some reason, using this code doesn't work - the JavaScript actually doesn't even load (this is a snippet, I am using an alert() in the window.onload() function and only this function makes it not display).

If I comment both cases (but not the default) it works. If I comment the content of the cases (the document.getElementById() statements) it doesn't work.

If I try the same construct with if clauses it works, so it doesn't come from the content of the cases, but the cases themselves it seems.

I am not sure what I am doing wrong since I am checking the parameter profil type and it's a string. I'm using double quotes (tested with single quotes too) in my cases, and I don't see a syntax error in here to cause the JavaScript not to load.

Upvotes: 0

Views: 51

Answers (1)

ElDoRado1239
ElDoRado1239

Reputation: 4048

Seems to work once you remove those PHP parts. I've also added a break statement after default. I am pretty sure your PHP inserts text that breaks the JS code.

http://jsfiddle.net/bbW25/

var idImp = document.getElementById("id_importeur");
function listUsers(profil){
 switch(profil.toUpperCase()){
  case "DGA":
   idImp.innerHTML = "DGA";
  break;
  case "INDUSTRIEL":
   idImp.innerHTML = "INDUS";
  break;
  default:
   idImp.innerHTML = "profil_err_users";
  break;
 }
}

Upvotes: 1

Related Questions