jQuery Select - call function on add/remove option

Thursday, 16 April 2009

This post is in response to a request by Dave in the comments section of my jQuery select cheat sheet post

Dave asked:
How do you bind an event that calls a function whenever a new 'option' tag is added to the 'select' tag?

The answer is kind of long so I thought it would be best to put it in a post so that everyone can read it.

In the 1.3 release of jQuery they have released a new function live. Unfortunately unlike the plug-in it is based on liveQuery it does not support the no-event style callback that liveQuery provides, which means we will need to use the plug-in. Hopefully this will become available in the future (although full credit should be given to Brandon Aaron for his awesome plug-in). Be sure to check out the documentation for more about the no-event callbacks.

Here is a link to the demo that shows how we can achieve a function call on both adding and removing an option to a select element.

You can view source on the HTML, but I'll show you the javascript as that's where the magic is.

It's a very simple demo, but it achieves it's purpose. You should be able to customize this and get it do to whatever you need.

$(document).ready(function(event) {
$("#myselect").data("size", $("#myselect option").size());

$("#myselect option").livequery(function() {
if ($("#myselect option").size() > $("#myselect").data("size")) {
alert('option added');
$("#myselect").data("size", $("#myselect option").size());
}, function() {
if ($("#myselect option").size() < $("#myselect").data("size")) {
alert('option removed');
$("#myselect").data("size", $("#myselect option").size());

$("#addoption").click(function() {

$("#removeoption").click(function() {


function addanoption() {
$("#myselect").append("<option value='1'>Apples</option>");

function removeanoption() {
$("#myselect option:last").remove();

We start of with a call to the jQuery data function which saves the current size of our select element for later reference.

We then use the liveQuery function to match any option that is added to our select element and the extra function call is used whenever the same option is unloaded from the select element. So the first half checks if the current size is greater than the original size (this is needed otherwise the function would be called at document.ready when it matches any initial elements), this is so we know that an addition has been made and then we call whatever function we would like. Similarly when an option is removed we confirm that the size of the select has been reduced (maybe this step is unnecessary, I'll leave to you to decide) and then it calls whatever function you would like for the remove.

blog comments powered by Disqus