Vishwajeet
Vishwajeet

Reputation: 1683

Dynamically created button not working properly

I created rows of table Dynamically by jquery, I also add a remove button on each row,and add an event on this button by which the row corresponding to that button(in a row) is removed when we click on that button,But my broblem is only upper three buttons are active and fired,and the buttons which are at last are not able to work.

$(function(){ 
    $('<input></input>')
        .attr({'type': 'button'})
        .val("Remove")
        .appendTo('table#AllSelectedTest tbody tr:first td:last')
    ; 
});

$(document).ready(function() { 
    $("table#AllSelectedTest tbody tr input").live({
        click: function(){
            $(this).closest('tr').remove(); 
        }
    })
});

I uses The above code For Generating a button and bind it with the events. My Problem is some button works and some are not

Upvotes: 0

Views: 225

Answers (2)

dku.rajkumar
dku.rajkumar

Reputation: 18568

its always good to give an id to element. try changing the code as below

$(document).ready(function(){   
   $('<input>').attr({type: 'button', id:"remove_button", value:'Remove'})
                     .appendTo('table#AllSelectedTest tbody tr:first td:last');

   $("#remove_button").live("click", function(){
                         $(this).closest('tr').remove();
        });
});

fiddle example : http://jsfiddle.net/vSUYj/1/

also if you are using jquery above 1.7, please make use on instead of live.

update: try this as well, in case above not working

 $(document).ready(function(){   
       var elem = $('table#AllSelectedTest tbody tr:first td:last');
       elem.append('<input type="button" id="remove_button" value="Remove"/>');

     $("#remove_button").live("click", function(){
         $(this).closest('tr').remove();
     });
 });

fiddle example : http://jsfiddle.net/vSUYj/

Upvotes: 2

kinakuta
kinakuta

Reputation: 9037

Without seeing your code, it's impossible to say for certain, but are you using .live() or .delegate() to assign the handlers for those buttons?

edit: should also be noted that those methods are deprecated in the latest version of jquery, and the new method is .on()

Upvotes: 1

Related Questions