Jquery and change() with more than 1 function?
Question
I am trying to find the best way to have a different function happen on change of my select box.
This is my select HTML
<select name="event-recurring">
<option selected="true">None</option>
<option value="daily">Daily</option>
<option value="weekly">Weekly</option>
<option value="monthly">Monthly</option>
</select>
My jquery is:
$('select[name=event-recurring] option:selected').change (function (){
//Will Do Something
});
How Do I tell it do something different on the different values?
Solution:
$('#event-recurring').change(function (){
var $select = $(this);
switch($select.val()) {
case "daily":
$('#recurring-options').remove();
$("<div id='recurring-options' class='row'><label>Choose:</label>Choose a Date</div>").insertAfter('#recurring');
break;
case "weekly" :
$('#recurring-options').remove();
$("<div id='recurring-options' class='row'><label>Choose:</label>Weekly</div>").insertAfter('#recurring');
break;
case "monthly":
$('#recurring-options').remove();
$("<div id='recurring-options' class='row'><label>Choose:</label>Monthly</div>").insertAfter('#recurring');
break;
default:
$('#recurring-options').remove();
break;
}
});
Solution
$('select[name=event-recurring]').change (function (){
var $select = $(this);
switch($select.val()) {
case "daily":
// do something
break;
case "weekly" :
// do something else
break;
default:
// default case
break;
}
});
I'd recommend giving the <select>
an id too and use that to select it as it will be faster than by name
OTHER TIPS
Pretty sure that this will work inside the change function:
$('select[name=event-recurring]').change (function (){
switch ($('option:selected', this).val()) {
case "daily":
// do something
break;
case "weekly":
// do something
break;
case "monthly":
// do something
break;
}
});
Do you means do thing different on different selected value?
If so, I believe you can use 'this' object in the function to refer the source of the event (the select in this case) and you can check its value using '.val()' or '.text()' to see what the value that is and process accordingly.
Hope this helps.
Use a subquery on the selected value and get it's value attribute as the discriminator for your action:
$('select[name=event-recurring]').change( function() {
var value = $(this).find(':selected').attr('value');
if (!value) { // none
do something
}
else if (value == 'daily') {
do something else
}
...
});