sKunKbad Posted August 19, 2011 Share Posted August 19, 2011 I'm wondering if there is a more efficient way to call one of the functions in the switch statement below (but without using eval(), or is eval() the best way to go? I just basically need to do a little client side validation in a multi page form, and if the processing function returns true or false, I'll either send the user to the next page or output error messages. switch(page){ case '1': var processing_function = part_1(); break; case '2': var processing_function = part_2(); break; case '3': var processing_function = part_3(); break; case '4': var processing_function = part_4(); break; case '5': var processing_function = part_5(); break; case '6': var processing_function = part_6(); break; case '7': var processing_function = part_7(); break; case '8': var processing_function = part_8(); break; case '9': var processing_function = part_9(); break; case '10': var processing_function = part_10(); break; } if( processing_function ){ // Do something }); Link to comment https://forums.phpfreaks.com/topic/245167-calling-function-via-a-switch-does-not-seem-efficient/ Share on other sites More sharing options...
nogray Posted August 19, 2011 Share Posted August 19, 2011 try this var processing_function = window['part_'+page](); Link to comment https://forums.phpfreaks.com/topic/245167-calling-function-via-a-switch-does-not-seem-efficient/#findComment-1259270 Share on other sites More sharing options...
sKunKbad Posted August 19, 2011 Author Share Posted August 19, 2011 Wow, that's a lot better! I was actually trying to do something like that initially, but didn't know I needed the square brackets. Thanks. Link to comment https://forums.phpfreaks.com/topic/245167-calling-function-via-a-switch-does-not-seem-efficient/#findComment-1259273 Share on other sites More sharing options...
Adam Posted August 19, 2011 Share Posted August 19, 2011 I would first validate the function exists, or you could run into a JS error: if (window['part_'+page]) { // ... } Link to comment https://forums.phpfreaks.com/topic/245167-calling-function-via-a-switch-does-not-seem-efficient/#findComment-1259329 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.