0

Possible Duplicate:
Binding dynamically created elements in jQuery

Is there a way I can change the following code:

$('#city')
        .focus(function () {
            $('option[value="99"]', this).remove();
            store.setItem($(this).attr('id'), $(this).val());
        })
        .change(function () {
            store.setItem($(this).attr('id'), $(this).val());
            $(this).attr("title", $("option:selected", this).attr("title"));
            $('#detailData').html("");
        });

So that it works for selects even if they have not yet been created as long as they have the class "update-title". for example:

<select class="update-title"> 

I saw some implementation using live but someone said it was not good to use. Also is there much of an overhead doing this. Would it be better for me to add the code after I am sure the selects have been created with document.ready() ?

Community
  • 1
  • 1
Angela
  • 3,269
  • 3
  • 22
  • 24
  • Something like [THIS](http://jsfiddle.net/M5hfH/) .. – adeneo Aug 30 '12 at 13:43
  • @DanielA.White Conceptually they're similar, but note that none of the answers to that question suggest `.on()`, which is *now* the best answer to this question. – msanford Aug 30 '12 at 14:55

4 Answers4

6

Have a look at on. This is a replacement for live which would do this for you.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

You need on:

$(document).on('change', '.update-title', function(event){

    // your business here

});

This way the document listens for any events triggered on .update-title elements, wether they were there at document load or not.

moonwave99
  • 21,957
  • 3
  • 43
  • 64
1

Best way is to use delegation - so you bind the event handler to a parent element that exists at the time the dom is loaded - It will in turn listen for events on the given elements and handle them

ex with jQuery 1.7+

$('body').on('click','.update-title', function(){ // <-- all click events will now bubble
// up to body - and it will listen for events from .update-title
    // code here
});

It is best practice to bind the event handler to the closest parent at dom load as you can see the overhead in binding to the body/document - all click events will bubble up - wheareas if you bind to a parent element only those inside that element will bubble up.

wirey00
  • 33,517
  • 7
  • 54
  • 65
0

Yes,you sure thtat the selects have been created with document.ready(), if the html is not loaded in ajax

alessio271288
  • 348
  • 1
  • 7