Reputation: 920
My jquery code :
//i can get the id correctly
id = $(this).parent().parent().children('td.idName').text();
//it seems that i have invoke the wrong function
$('.confirmDeleteButton').click(function () {
$(".idName:contains('" +id + "')").parent().remove();
});
I have a table with many row , when i click the confirmDeleteButton ,it should delete the row .
for example if id = 1
it means that i should delete this row
<tr>
<td class="idName">1</td> //id =1;
<td><button class="delete " > delete</td>
</tr>
but in fact , it delect
<tr>
<td class="idName">1</td> //id = 1
<td><button class="delete " > delete</td>
</tr>
<tr>
<td class="idName">10</td> //id =10
<td><button class="delete ">delete</td>
</tr>
it seems that if id = 1 it will delete all row with 1 such as 11 ,111, 101,21 etc.
My problem is that What is the correct way to delete the correct row by id?
Upvotes: 1
Views: 47
Reputation: 48357
Using contains
method it's a wrong thing. You can use forEach
method which accepts a callback
method.
var id=1;
$('.confirmDeleteButton').click(function () {
Array.from($(".idName")).forEach(function(item){
if($(item).text().trim()=="1")
$(item).parent().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="idName">1</td>
<td><button class="delete"> delete</td>
</tr>
<tr>
<td class="idName">1</td>
<td><button class="delete"> delete</td>
</tr>
<tr>
<td class="idName">10</td>
<td><button class="delete">delete</td>
</tr>
</table>
<button class="confirmDeleteButton">Confirm</button>
Upvotes: 1
Reputation: 136094
What is the correct way to delete the correct row by id?
Don't do that, delete the row relative to the button you've clicked.
$('.delete').on('click',function(){
$(this).parents("tr").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="idName">1</td>
<td><button class="delete" > delete</td>
</tr>
<tr>
<td class="idName">10</td>
<td><button class="delete">delete</td>
</tr>
</table>
Upvotes: 4