jQuery execute function when option is selected from option object

30,464

Solution 1

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);
    }
});

Solution 2

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

Solution 3

What you can try is binding the change() event on the select element itself. From there, assuming you have a valid function for each option, you can call an individual option's callback:

$('select').change(function() {
  var type = $(this).val();
  switch(type) {
  }

  // Alternatively, you can try this as well:
  $(this).find('option:selected').each(function() {
  });
});

Solution 4

If you are saying you want to assign individual functions to each option element you can do something like this:

var options = [{"value" : "1",
                "display" : "One",
                "fn" : function() { console.log("One clicked"); }
               },
               {"value" : "2",
                "display" : "Two",
                "fn" : function() { console.log($(this).val() +  " clicked"); }
               }];

var $select = $("select").on("change", function() {
    var opt = this.options[this.selectedIndex];
    $(opt).data("fn").call(opt);
});

$.each(options, function(i, val) {
    $select.append(
        $("<option/>").attr("value", val.value)
                      .text(val.display)
                      .data("fn", val.fn)
    );
});

​Demo: http://jsfiddle.net/6H6cu/

This actually attaches functions to each option using jQuery's .data() method, and then on click/keyup on the select element it calls the appropriate options function (setting this to the option).

In my opinion that is way overkill, but it seems to be what you are asking.

I guess a simpler version would be something like:

var optionFunctions = {
   "1" : function() { ... },
   "2" : function() { ... },
   ...
};

// code to create the options omitted

$("select").on("change", function() {
    var fn = optionFunctions[$(this).val()];
    if (fn)
       fn.call(this.options[this.selectedIndex]);
});
Share:
30,464
GoldenNewby
Author by

GoldenNewby

Updated on July 23, 2022

Comments

  • GoldenNewby
    GoldenNewby almost 2 years

    I am dynamically creating the options for a select element using jQuery. Is it possible in jQuery to setup a function to be executed when that option is selected?

    I know I can detect the change of the entire select element, but is it possible to specify this on a per-option basis? Maybe something like this:

    $('<option />').onselect(function(){
    
     // do something
    
    });
    

    Edit: If it's not possible to specify a function that get's executed when a specific option is selected, is it possible to bind a function to an element in jQuery? It would make my logic cleaner by allowing me to just simply execute that function assigned to the option in the .change for the select.

  • GoldenNewby
    GoldenNewby about 12 years
    Well I know I can watch to see if the select element changes, and to things based on that. What I'd like to do is assign a function to each option.
  • David Hellsing
    David Hellsing about 12 years
    You can do a switch statement in the handler based on the option:selected, it would be the same result but more efficient.
  • David Hellsing
    David Hellsing about 12 years
    @GoldenNewby see my edit for another option using function assignment to each element.
  • Pitto
    Pitto over 10 years
    This is so beautiful and useful that even knowing I shouldn't comment with such a useless comment I'll do it anyway: thanks. Oh, thanks.