JamesB JamesB - 23 days ago 8
jQuery Question

Make button in a table cell to change the color of the row it's in

I'm trying to add a class to the same row that the button I click on is in. I use the jquery "closest" function but it doesn't work. I also tried .parent etc. Anyone know what I do wrong?

<table class="table table-striped table-bordered table-hover">
<tbody class="">
<tr class=''> //I want to change this class
<td style=''><div class='btn btn-xs btn-success cellButton'></td>
</tr>
</tbody>




$('.cellButton').on('click', function(){
$(this).closest("tr").addClass('info')
}


EDIT: I realise now that the code I posted should work (I simplified it before posting), and the problem is because it's referencing $(this) from a different function. This is the real javascript function:

$('.cellButton').on('click', function(){


var formData = {
'action': 'blabla',
'ID': ID,
};

$.ajax({
type: 'POST',
url: 'includes/jquery-actions.php',
data: formData,
dataType: 'json',
error: function (response) {
alert("error!");
},
success: function (response) {
var row = $(this).parents("tr"); //$(this) here not referencing the HTML button?)
row.addClass('warning');
}
})


}

Answer Source

Your version is working. Also you can use jQuery#parents function. Give it the selector, it will tries to find the closest one and return that element.

parents

$('.cellButton').on('click', function() {
    $(this).parents("tr").addClass('info');
});
.info {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped table-bordered table-hover">
<tbody class="">
    <tr class=''> 
        <td style=''><div class='btn btn-xs btn-success cellButton'>Click me</td>
    </tr>
</tbody>

closest

$('.cellButton').on('click', function() {
    $(this).closest("tr").addClass('info');
});
.info {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped table-bordered table-hover">
<tbody class="">
    <tr class=''> 
        <td style=''><div class='btn btn-xs btn-success cellButton'>Click me</td>
    </tr>
</tbody>

UPDATED

There is an issue with context.

You can keep your this in above the ajax request and use that variable inside the function

var that = this;

...

success: function (response) {
      var row =  $(that).parents("tr"); 
      row.addClass('warning');
}

Or just use arrow functions

success: (response) => {
      var row =  $(this).parents("tr"); 
      row.addClass('warning');
}