Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector does not work on dynamic created content in IE7 and IE8

I have this elements on my site which are added dynamically on jQuery's document.ready function.

The problem is that I can't select those element using regular jQuery selectors. The JavaScript runs fine in IE9 and other browsers. I think the reason why it does not work is because the content that I'm trying to alter is added dynamically.

How do I solve this issue?

Code:

$('.dynamic').each(function(index)
    {
        $('textarea, input[type=radio], input[type=checkbox], select, input[type=text]', this).each(function()
        {

            var array = $(this).val().split('|||');

            var elements = new Array();

            var target = String('.dynamic_'+$(this).attr('id'));        

            $(target).each(function() //this does nothing in ie7 and 8, seems the target selector is messed up :S
            {
                elements.push($(this)); 
            });

            for (val in array)
            {
                var count = Number(val);    
                $(elements[count]).val(array[val]);         
            }
        });
    });
like image 691
Richard Avatar asked Aug 30 '11 15:08

Richard


1 Answers

I don't see any specific reason for targeting a javascript to IE7 or IE8 since we are all talking about jQuery here. I believe the real problem is not related to the browser itself, it's the misuse of event bindings.

You have to use the live() or delegate() method. They both will assign the event to the already existing elements in DOM and to the elements created dynamically.

Ex:

$(".element").live("click", function() {  
    //dazzling stuff here
});

And with delegate:

$('.element').delegate('.context-element', 'click', function() {  
    //dazzling stuff here 
});

I suggest you to use deletage() instead of live() since I already experienced many bugs related to event bubbling in some browsers while using live. Also delegate() is much faster too, so if you're working on a very intense application in terms of DOM manipulation, better to use it.

like image 99
marcio Avatar answered Oct 19 '22 23:10

marcio