When selecting a value from the first select, the values ​​in the second select are loaded. But, if you select a different value from the first select, the values ​​in the second select are loaded, but the old ones are not cleared.

<div class="form-group"> <div class="row"> <label for="name" class="col-sm-3 control-label">Авто <span class="text-danger">*</span></label> <div class="col-sm-4"> {!! Form::select('car', $cars, null, ['class' => 'form-control']) !!} </div> <div class="col-sm-5"> <select name="car_options" class="form-control"> </select> </div> </div> </div> 

code itself

 <script type="text/javascript"> $('select[name=car]').change(function(e) { var car_option_id = $('select[name=car_options]'); e.preventDefault(); $.ajax({ type: 'post', dataType: 'json', url: 'url', data: { car_id: $('select[name=car]').val() }, headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }, success: function(data){ $.each(data, function(index, car_option) { car_option_id.append("<option value=" + car_option.id + ">" + car_option.name +"</option>") }); console.log(data); } }); }); </script> 

    1 answer 1

     car_option_id.append 

    append adds to the existing, and does not overwrite, I in your place would first do a cleanup of the select for example like this car_option_id.empty ();

      success: function(data){ car_option_id.empty(); $.each(data, function(index, car_option) { car_option_id.append("<option value=" + car_option.id + ">" + car_option.name +"</option>") }); console.log(data); } 
    • Exactly what is needed. Thank. - Alex_01
    • then mark the answer as correct. not at all. - Boris Runs
    • 4 minutes you have to wait) wait) - Alex_01