I have the following select lists which are in table cells. The select lists are identical however within each cell is a unique set of hidden values, namely model and year. I basically want the background colour to update within the cell containing the select list I am changing, on success, via ajax. I almost have it except it changes all cells.
<td>
<input type="hidden" name="model" value="2" />
<input type="hidden" name="year" value="2020" />
<select name="select-vehicle">
<option value="0"></option>
<option value="1">Car 1</option>
<option value="2">Car 2</option>
</select>
</td>
<td>
<input type="hidden" name="model" value="1" />
<input type="hidden" name="year" value="2019" />
<select name="select-vehicle">
<option value="0"></option>
<option value="1">Car 1</option>
<option value="2">Car 2</option>
</select>
</td>
$ ('select[name="select-vehicle"]').change(function() {
var data = {
'car_id' : $(this).val(),
'model_id' : $(this).siblings('input[type="hidden"][name="model"]').val();
'year' : $(this).siblings('input[type="hidden"][name="year"]').val();
$.ajax({
url: 'cars/saveVehicle',
data: data,
method: 'post',
success: function(response) {
$('select[name="select-vehicle"]').closest('td').addClass('bg-success');
},
error: function(jqXHR, textStatus, errorThrown){
var errorAlert = $(thisForm).find('.alert');
$(errorAlert).find('p').text('Unable to save');
$(errorAlert).show();
},
complete: function(){
$(errorMessage).hide();
}
});
event.preventDefault();
});
CodePudding user response:
You need to capture $(this)
as a variable that you can reference in your ajax later:
$('select[name="select-vehicle"]').change(function() {
let _this = $(this); // capture it here
var data = {...}
$.ajax({
...
success: function(response) {
// then access it here
_this.closest('td').addClass('bg-success');
}
...
});
event.preventDefault();
});