2

My project is C# MVC.

I have a table whose last row contains a dropdownlist with an 'Add' button. On clicking the 'Add' button, a row is added to the table via JQuery. This works fine.

Part of the row that is added is a 'Remove' button that I want to use to delete the row.

Strange thing is, the "Remove" button's click event is not being picked up by JQuery. It is exactly the same as the "Add" button, just with a different ID. Anyone know why this would be so? Code below.

    $('#AddBuyCondition').click(function () {
        alert("abc");
        var conditionID = +$("#BuyConditionList").val();
        var conditionText = $("#BuyConditionList").find('option:selected').text();
        $('#BCDropDownRow').before('<tr><td>' + conditionText + '</td><td><button id="RemoveBuyCondition" type="button" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-minus"></span></button></td></tr>');
    });

    $('#RemoveBuyCondition').click(function () {
        alert("rbc");
    });

2 Answers 2

5

You need to use event delegation here since your button has been added dynamically to the DOM:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.

$('#BuyConditions').on('click', '#RemoveBuyCondition', function() {
    alert("rbc");
});

So basically in your case, event delegation will helps you to attach click event to dynamically added button element.

Also, in order to prevent duplicated id, you should use class instead of id for your button.

......'</td><td><button type="button" class="RemoveBuyCondition btn btn-default btn-xs">......

then you can change the jQuery code to:

$('#BuyConditions').on('click', '.RemoveBuyCondition', function() {
    alert("rbc");
});
Sign up to request clarification or add additional context in comments.

2 Comments

Indeed! Thank you kindly. Just to clarify the answer, the name of the table is "BuyConditions". I changed the above answer to the below and it works fine. $('#BuyConditions').on('click', '#RemoveBuyCondition', function() { alert("rbc"); });
Felix has it. Just to clarify the answer, the name of the table is "BuyConditions". I changed the above answer to the below and it works fine. $('#BuyConditions').on('click', '#RemoveBuyCondition', function() { alert("rbc"); });
0

try by live function

$('#AddBuyCondition').live('click',function()
{ 
  alert("abc");
});

1 Comment

The live() function is now deprecated. You should avoid using it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.