Tengo las siguientes listas de selección que están en celdas de tabla. Las listas de selección son idénticas; sin embargo, dentro de cada celda hay un conjunto único de valores ocultos, a saber, modelo y año. Básicamente, quiero que el color de fondo se actualice dentro de la celda que contiene la lista de selección que estoy cambiando, en caso de éxito, a través de ajax. Casi lo tengo excepto que cambia todas las celdas.
<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(); });Debe capturar $(this) como una variable a la que puede hacer referencia en su ajax más adelante:
$('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(); });