Reputation: 960
If I have the following selectbox:
<select id="a1" multiple>
<option>Apple</option>
<option>Banana</option>
<option>Carrot</option>
<option>Dates</option>
<option>Eggs</option>
<option>French fries</option>
</select>
What is the proper way to write a conditional if
/ else
statement such that certain functions are executed only if some items are selected?
Meaning:
if Apple or Banana selected, then if
condition #1 is met and code fires
but if Carrot or Dates or Eggs selected, then if
condition #2 is met and different code fires
etc.
EDIT: I guess I used the items in this array as an example, but the most useable construct would peg the condition to the selected index (or indices), not necessarily just to the string values. That way, any selectbox could use the conditional argument, irrespective of the values therein.
Upvotes: 0
Views: 92
Reputation: 253308
One approach is to use a map, of relevant indices to relevant functions to be called on those indices, for example:
function functionOne() {
console.log('functionOne called');
}
function functionTwo() {
console.log('functionTwo called');
}
var functionMap = {
'0-1-2': function(){
functionOne();
},
'4-5': function(){
functionTwo();
}
};
$('select').change(function () {
var valueString = $(this).find('option:selected').map(function () {
return $(this).index();
}).get().join('-');
if (functionMap.hasOwnProperty(valueString)) {
functionMap[valueString]();
}
});
References:
Upvotes: 1
Reputation: 547
$('#a1').change(function(){
if($('#a1').val() == 'Carrot' || $('#a1').val() == 'Bannana'){
alert('condition #1');
}
});
Upvotes: 0