Reputation: 25
I have a javascript function that dynamically creates a button whose ID calls a value that will make it unique.
id='btnRemove_" + rowId + "'
Because it has an id that calls a value, how would I use the hide()
method to hide this button on certain conditions?
var createChildTableRowDeleteButton = function(rowId, title) {
return $("<button type='button' class='btn btn-sm btn-danger remove' id='btnRemove_" + rowId + "' title='" + title + "'>" +"<span class='delete glyphicon white glyphicon-remove'></span></button>").click(function() {
$(this).closest('tr').remove();
});
};
Upvotes: 0
Views: 135
Reputation: 337560
The standard approach to take when appending dynamic content is to use delegated event handlers. This way you don't need to write ugly code to generate, maintain or validate dynamically id
attributes. The pattern looks something like this:
// function to create the button
let createChildTableRowDeleteButton = title => `<button type="button" class="btn btn-sm btn-danger remove" title="${title}">${title}<span class="delete glyphicon white glyphicon-remove"></span></button>`;
// delegated event handler to handle button click
$('table').on('click', '.remove', e => {
$(e.target).closest('tr').remove();
});
// call the function to create the button
$('td').append(createChildTableRowDeleteButton('foo bar'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td></td>
</tr>
</table>
Upvotes: 2