Это потому, что кнопка с идентификатором deletesupLoc
не существует в DOM, когда вы вызываете .click()
.Поскольку он был добавлен динамически с использованием вашего скрипта, jQuery еще не знает о существовании этой кнопки.Поэтому вам нужно добавить вызов к $(document).on('click')
, когда вы создаете кнопку для добавления прослушивателя событий во вновь созданный элемент.
Я немного изменил ваш код, чтобы идентификатор для каждой кнопки был уникальным (если только одно и то же имя не введено дважды - вы можете либо проверить это и убедиться, что это не может произойти, либо добавить количество вхождений +1 до конца идентификатора), который затем позволяет удалить соответствующую строку в таблице:
// Find and remove selected table rows
function deleteRow(buttonId) {
$("#" + buttonId).each(function(){
{
$(this).parents("tr").remove();
}
});
};
$(document).ready(function(){
$(".add-supplying-location-row").click(function(){
var supname = $("#supplyingLocation").val();
$('#supplyingLocation').val('');
var buttonId = "deletesupLoc" + supname.replace(" ", "");
var supDeleteButton = $("<input type='button' name='supplyingLocRecord' value='Delete' id='" + buttonId + "'>");
$(document).on('click', '#' + buttonId, function() { deleteRow(buttonId); });
var supRow = $("<tr>");
supRow.append("<td>").append(supname);
supRow.append("<td>").append(supDeleteButton);
$(".sup-loc-table table tbody").append(supRow);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6 col-md-5">
<div class="form-group">
<label class="control-label" for="supplyingLocation">Supplying to Location <span class="text-danger">*</span></label>
<div class="input-group">
<input type="text" class="form-control" placeholder="Enter Supplying Location Name" name="supplyingLocation" id="supplyingLocation" required="required">
<div class="input-group-btn">
<button class="btn btn-primary add-supplying-location-row" type="button">Add Location </button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
<div class="col-sm-5">
<div class="listing-table">
<div class="table-responsive sup-loc-table">
<table class="table table-bordered">
<thead>
<tr>
<th>Supplying to Location</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>