jQuery execute function when option is selected from option object
You can delegate a change
event to the document and attach an event handler to the select
element. This allows for runtime manipulation:
$(document).on('change', 'select', function() {
console.log($(this).val()); // the selected options’s value
// if you want to do stuff based on the OPTION element:
var opt = $(this).find('option:selected')[0];
// use switch or if/else etc.
});
Or if you insist on creating functions for each OPTION, you can do:
$('<option>').data('onselect', function() {
alert('I’m selected');
});
$(document).on('change', 'select', function(e) {
var selected = $(this).find('option:selected'),
handler = selected.data('onselect');
if ( typeof handler == 'function' ) {
handler.call(selected, e);
}
});
You can use onchange handler to the select:
<select name='numbers' id='numbers'>
<option value='1' selected='selected'>One</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
</select>
<script>
$('#numbers').change(function () {
if ($(this).val() === '1'){
function1();
}
if ($(this).val() === '2'){
function2();
}
});
</script>
Best Regards