9

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.

2
  • 1
    Why can't you just use $(document).on('change', 'select', function() {...}); to bind it dynamically? Commented Mar 12, 2012 at 4:40
  • What happens when the select changes between the options isn't similar for each option that the user can select. So rather than having to check the value of the select, then do separate instructions based on that, I'd prefer it if I could just create individual functions on a per-option basis. Commented Mar 12, 2012 at 4:43

4 Answers 4

13

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);
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

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.
You can do a switch statement in the handler based on the option:selected, it would be the same result but more efficient.
@GoldenNewby see my edit for another option using function assignment to each element.
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.
7

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

Comments

2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.