2

I've got the following code which depending on a url parameter changes and then hides a select option on a form. ie www.example.com?type=images

Eventually there will be over 20 different parameters. I'd like to know of a better way than having a huge amount of if elses. Just an outline of how to do it is fine, I'm new to this, so I'd like to be able to take the answer and learn from it. Thanks.

var type = getURLparameter('type'); //from another function

if (type == "images"){
    var selectDiv =('divid');
    var selectField = ('selectid');
    document.getElementById(selectField).options[1].selected=true;
    document.getElementById(selectDiv).style.visibility="hidden";
}
else if (type == "pizza") {
    var selectDiv =('divid');
    var selectField = ('selectid');
    document.getElementById(selectField).options[2].selected=true;
    document.getElementById(selectDiv).style.visibility="hidden";
}
else (type == "cheese") {
    var selectDiv =('divid');
    var selectField = ('selectid');
    document.getElementById(selectField).options[3].selected=true;
    document.getElementById(selectDiv).style.visibility="hidden";
}
tekknolagi
  • 10,663
  • 24
  • 75
  • 119
K Groll
  • 518
  • 2
  • 8
  • 18
  • 3
    What about [switch](http://www.w3schools.com/js/js_switch.asp)? – David Rodrigues Nov 29 '11 at 01:17
  • 1
    I'd format your HTML and such so that you won't need special cases for everything. – Blender Nov 29 '11 at 01:18
  • I must agree with Blender's comment. If your structure is well done you shouldn't need the if-elses *or* a switch statement. – Stephen P Nov 29 '11 at 01:23
  • 1
    Seems to me that in the example code given the only thing changing in each case is the index into the `.options` collection, so whether you use a switch or keep the if/else if/else if structure the line to select the appropriate option is the only thing you need in each case - the other three lines can be moved up to before the first if (or before the switch if you, well...switch to that). – nnnnnn Nov 29 '11 at 01:26
  • How would I do that? It's just one select field. – K Groll Nov 29 '11 at 01:29
  • So the select and the div are actually the same every time? You'd store them in a variable once, and refer to them. If this code is inside a function, store them outside the function. – RightSaidFred Nov 29 '11 at 01:32
  • Ok that makes sense. Also regarding the HTML, I can't change it, It's a hosted 3rd party form. Thanks for the options all. – K Groll Nov 29 '11 at 01:38
  • What did I do to get a downvote? – K Groll Nov 29 '11 at 01:42
  • Related: http://stackoverflow.com/questions/3640843/refactoring-a-large-block-of-chained-if-else-statements – BalusC Nov 29 '11 at 02:00
  • related article http://encosia.com/first-class-functions-as-an-alternative-to-javascripts-switch-statement/ – GibboK Feb 05 '15 at 18:25

7 Answers7

10

In the interest of not repeating code, I'd write your code like this with a lookup table for the index num and no repeated code for each option:

var typeNum = {
    images: 1,
    pizza: 2,
    cheese: 3
};

var type = getURLparameter('type');

if (type in typeNum) {
    document.getElementById('selectid').options[typeNum[type]].selected = true;
    document.getElementById('divid').style.visibility = "hidden";
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
6

Use a switch:

var selectDiv   = document.getElementById('divid'), 
    selectField = document.getElementById('selectid');

switch(type){
    case "images":
        selectField.options[1].selected=true;
        selectDiv.style.visibility="hidden";
    break;

    case "pizza":
        selectField.options[2].selected=true;
        selectDiv.style.visibility="hidden";
    break;

    case "cheese":
        selectField.options[3].selected=true;
        selectDiv.style.visibility="hidden";
    break;
}
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
4

Put them in an object and look up the one you need.

var type_table = {
    images: {
        div_id: 'somevalue',
        select_id: 'somevalue',
        option_index: 0
    },

    pizza: {
        div_id: 'somevalue',
        select_id: 'somevalue',
        option_index: 1
    },

    cheese: {
        div_id: 'somevalue',
        select_id: 'somevalue',
        option_index: 2
    }
};

then...

var the_type = type_table[ type ];

document.getElementById(the_type.select_id).options[the_type.option_index].selected=true;
document.getElementById(the_type.div_id).style.visibility="hidden";

If the IDs are actually all the same, then naturally you should cache those elements instead of reselecting them, and the only thing you'd need to store in the table would be the index number.


It sounds like the only unique part is the index. If so, do this:

var type_table = {
    images:0,
    pizza:1,
    cheese:2, // and so on
};

var the_div = document.getElementById('div_id');
var the_select = document.getElementById('select_id');

then inside the function that is running the code...

the_select.options[ type_table[ type ] ].selected=true;
the_div.style.visibility="hidden";
RightSaidFred
  • 11,209
  • 35
  • 35
  • Also used some of this solution. If I had some more rep. I'd upvote for sure. Thanks for your help. – K Groll Nov 30 '11 at 00:31
3

maybe a switch statement would help you

http://www.tutorialspoint.com/javascript/javascript_switch_case.htm

also, set the selectDiv before everything to reduce the amount of code :)

switch(type) {
    case 'images':
        //blah
        break;
}
tekknolagi
  • 10,663
  • 24
  • 75
  • 119
  • 2
    @PHPBree: You could have offered a [decent reference](https://developer.mozilla.org/en/JavaScript/Reference/Statements/switch) or [two](http://es5.github.com/#x12.11) so that tekknolagi would know somewhere better to look in the future. – mu is too short Nov 29 '11 at 01:33
  • @muistooshort this is true, but I just googled `javascript switch statement` and W3Schools is the first that came up... 's what I get for being lazy, i guess. Then again, I did answer first! and the w3schools page was right! – tekknolagi Nov 29 '11 at 01:34
  • 1
    That's part of the problem with w3fools: they've gamed the system to get themselves to the top of the Google ranks so people unwittingly find them and assume they're associated with the real W3. Bookmark the MDN and es5.github.com links and go straight there in the future; any HTML or CSS searches googling should include "site:w3.org" to get the real thing. – mu is too short Nov 29 '11 at 01:39
  • 1
    @muistooshort damn! didn't know that about w3fools and those are great resources! – tekknolagi Nov 29 '11 at 01:41
0

I know this is a very old question, but wanted to offer an alternative solution, I like this approach because it's concise, while still being very easily readable

const type = getURLparameter('type'); //from another function
const images = type === 'images' && 1
const pizza = type === 'pizza' && 2
const cheese = type === 'cheese' && 3
const option = images || pizza || cheese

document.getElementById(selectField).options[option].selected=true;
0
document.getElementById(selectField).options[(type == "images" ? 1 : (type == "pizza" ? 2 : 3))].selected=true;
document.getElementById(selectDiv).style.visibility="hidden";
Godwin
  • 9,739
  • 6
  • 40
  • 58
0

you could use an array of functions, similar to the ever popular dictionary solution in c#,

var mySwitch={};
mySwitch['images'] = function(){ 
    var selectDiv =('divid');
    var selectField = ('selectid');
    document.getElementById(selectField).options[1].selected=true;
    document.getElementById(selectDiv).style.visibility="hidden";
};
mySwitch['pizza'] = function(){...};

then do

mySwitch[type]();
Jeff Lauder
  • 1,247
  • 8
  • 14