I have some set of if
conditions for a particular array using JavaScript.
activity
is the array containing 10-12 items. This array is converted to a multiple select dropdown. Depending upon the value selected, I need to hide and show divs. I also need to set values of another input choice as "NA".
Here's the code written for the onchange
of that multiple select dropdown.
activity = ["strategy session","sessions","virtual",...,"Other"]
if (activity.indexOf("strategy session") != -1) {
$("#FoPStrategySession").show();
}
if (activity.indexOf("sessions") != -1) {
$("#acprojectname").show();
if (supportmodel == "Level") {
$(".accombohide").hide();
$("[title='Test']").val("NA");
$("[title='Test2']").val("NA");
}
}
if (activity.indexOf("virtual") != -1) {
if (supportmodel == "Level") {
$(".lvl3_consult").hide();
$("[title='Test']").val("NA");
$("[title='Test2']").val("NA");
}
}
if (activity.indexOf("Other") != -1) {
$("#acactivityother").show();
}
Is there any other way to efficiently write this code using switch case or any other method?
2 Answers 2
You could for example put all actions in an object
var actions = {
"session": function() { console.log("session"); },
"virtual": function() { console.log("virtual"); },
};
and loop over its keys:
var activities = [
"session",
"virtual",
"other"
];
for(let i = 0; i < activities.length; i++) {
let action = actions[activities[i]];
if (action) action();
}
I would think you might benefit from the approach of defining individual callbacks to do whatever DOM manipulation you need done for each of your option values.
That might look something like:
// configure your callbacks
var multiSelectCallbacks = {
'acactivityother': function() {
("#acactivityother").show();
},
'virtual': function() {
if (supportmodel == "Level") {
$(".lvl3_consult").hide();
$("[title='Test']").val("NA");
$("[title='Test2']").val("NA");
}
},
// etc.
}
To see this might be used, let's take a step back to where you bind your event handler for the dropdown menu (something you are not showing in your code)
That might need to look something like this:
$('#your_dropdown').on('change', function() {
// get all selected options
var selectedOptions = $(this).find('option:selected');
// loop through selected options firing off callbacks
$.each(selectedOptions, function() {
var activity = $(this).val();
multiSelectCallbacks[activity]();
}
}
activity
contain multiple types you check for? For example, canactivity = ["sessions", "virtual"]
? \$\endgroup\$activity
contain? What issupportmodel
? If you need to, in essence, detect the presence of the value of "session", "virtual", etc. in the array, then I question whether an object with property names matching the values be used to allow direct O(1) lookup rather than having to iterate an entire array looking for the presence of the value. \$\endgroup\$