Dav*_*son 2 c# asp.net-mvc jquery jquery-events
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");
});
Run Code Online (Sandbox Code Playgroud)
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");
});
Run Code Online (Sandbox Code Playgroud)
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">......
Run Code Online (Sandbox Code Playgroud)
then you can change the jQuery code to:
$('#BuyConditions').on('click', '.RemoveBuyCondition', function() {
alert("rbc");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
683 次 |
| 最近记录: |