Question

I have two selects that both have use a function to add elements to the other select. Here's what I have:

$("#lecturers option").dblclick(function () 
{
    var element = $("#lecturers option:selected");
    var value = element.val();
    element.remove();
    var values = value.split(";")

    $("#selected_lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');

});

and vice versa:

http://jsfiddle.net/VJAJB/

It somehow only works once, and the newly added elements don't trigger the function.

Any idea on how to fix this?

Was it helpful?

Solution

The issue is how you bind the dblclick function to the elements. The current selector only returns the option elements you have in your select element at the time of binding. To alter this, you can use delegated events.

$('#lecturers').on('dblclick', 'option', function() {
    //Do stuff here
});

This makes sure that any option element you add to the select element will trigger this event when it is double clicked.

Here is an updated fiddle: http://jsfiddle.net/VJAJB/4/

Please note that other users have given you solutions that will work. However, best practice is to limit the number of events bound to the document itself. Whenever possible, you should bind delegated event listeners to the nearest non changing element.

OTHER TIPS

This happens because the handler doesn't get bound to the new elements. You can do it like this, which will bind it to a descendant (in this case body) and specify the selector it will be applied to:

$('body').on('dblclick', '#lecturers option', function () 
{
    var element = $("#lecturers option:selected");
    var value = element.val();
    element.remove();
    var values = value.split(";")

    $("#selected_lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');
});

$('body').on('dblclick', '#selected_lecturers option', function () 
{
    var element = $("#selected_lecturers option:selected");
    var value = element.val();
    element.remove();
    var values = value.split(";")

    $("#lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');

});

If both have a parent/descendant element that is present at the time of binding, you can use that instead of 'body' to improve performance.

Fiddle: http://jsfiddle.net/VJAJB/2/

You need to use on method instead. In latest jQuery versions is:

$( document ).on( "dblclick", "#lecturers option", function () 

Updated jsFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top