I'm trying to delete a selected row in a table using jQuery.
This is my html markup:
<table id="resultTable">
<tr id="first">
<td>c1</td>
<td>c2</td>
</tr>
<tr id="second">
<td>c3</td>
<td>c4</td>
</tr>
</table>
<button id="del">Clear</button>
This is the script I'm using..
<script>
$(document).ready(function () {
var tid="";
$('#resultTable tr').click(function (event) {
tid=$(this).attr('id');
alert(tid); //trying to alert id of the clicked row
});
$("#del").click(function(){
alert("removing "+ tid);
$(tid).remove();
});
});
</script>
I'm declaring a global variable "tid" to obtain "rowId" and using the same variable in both click() function. But I'm unable to delete the corresponding row, please help me
Concatenate #
to make it valid ID
selector, without #
, jQuery will look for <first>/<second>
elements
$(document).ready(function() {
var tid = "";
$('#resultTable tr').click(function(event) {
tid = $(this).attr('id');
});
$("#del").click(function() {
console.log(tid);
if ($('#' + tid).length) {
$('#' + tid).remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table id="resultTable">
<tr id="first">
<td>c1</td>
<td>c2</td>
</tr>
<tr id="second">
<td>c3</td>
<td>c4</td>
</tr>
</table>
<button id="del">Clear</button>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments