Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to bind events during element concatenation in a loop?

Fiddle Example

The following is an example where several buttons are rendered via a loop. I was wondering if it is possible to bind events to each button as well during the loop before the buttons are appended to a container. My example doesn't work.

Jquery

function render(){

   var input = '',
       array = [{'name':'Confirm','title':'This'},{'name':'Cancel','title':'That'}] 

   $.each(array,function(k,obj){
       var name = obj.name;
       input += '<h3>'+obj.title+'</h3>';
       input += '<input type="submit" name="'+name+'" value="'+name+'"/>';

       $(input).find('[name="'+name+'"]').click(function(){

           alert(name)
           /*** do some ajax things etc ***/

       })

   })

   return input;
}

$('#box').append(render())
like image 876
RedGiant Avatar asked Feb 01 '26 12:02

RedGiant


1 Answers

Yes but I wouldn't do it the way you are:

function render(target){

   var array = [{'name':'Confirm','title':'This'},{'name':'Cancel','title':'That'}] 

   $.each(array,function(k,obj){
       var name = obj.name;
       var h3 = $('<h3/>').text(obj.title);
       var input = $('<input/>')
                     .attr('type', 'submit')
                     .attr('name',name)
                     .val(name);

       input.click(function() {alert('test');});

       target.append(h3);
       target.append(input);
   })

}

$(document).ready(function(){
    render($('#box'));
});

So create jquery objects that will be rendered, then attach the event to these objects. Then once the object is built ask jquery to render them.

This way jquery can keep track of the DOM elements, in your example your stringfying everything. Jquery hasn't built the DOM element at the point where your attempting to bind to them.

Fiddle

like image 80
Liam Avatar answered Feb 03 '26 03:02

Liam