Get the old selected value of a dynamicaly filled dropdown

Viewed 54

I have two relative dropdowns, when selecting the categories from the first dropdown, the suppliers are automatically filled from the database into the second dropdown using this script:

<script>
   $('#first-choice').change(function(){

        if( $('#first-choice :selected').length > 0){
            var selectednumbers = [];
            $('#first-choice :selected').each(function(i, selected) {
                selectednumbers[i] = $(selected).val();
            });
            $.ajax({
                url: '{{ url('get_fournisseurs') }}',
                method:'GET',
                data: {selectednumbers: selectednumbers },
                dataType: 'json',
                success: function(dataResult){

                    var resultData = dataResult.data;
                    $('#second-choice').empty();
                    $.each(resultData, function(i,row){
                        //$('#second-choice').append(new Option( row.id+'-'+row.nomSociete, row.id));
                        $('#second-choice').append(`<option value="${row.id}" {old('fournisseur') = ${row.id} ? 'selected' : ''} >
                                   ${row.id+'-'+row.nomSociete}
                              </option>`);
                    })
                }//value="{{$s->id}}" {{(collect(old('categorie'))->contains($s->id)) ? 'selected' : '' }}
            });
        }
    });
</script>

now in case of an error all my inputs are still filled except for the second dropdown (id="second -choice") it's empty, i want to have the old value before the error:

here is the code of my dynamic dropdown:

<div class="form-group col-md-6 col-sm-12">
    <b for="donationinput4">Fournisseur<span style="color: #fbb710;">*</span></b>
    <div class="input-group">

        <select class="custom-select @error('fournisseur') is-invalid @enderror" name="fournisseur" id="second-choice">
            <option value="">---------Selectionner un fournisseur---------</option>
        </select>
        <div class="input-group-append">
            <a href="{{ url('fournisseurs/create') }}" class="btn btn-pink" type="button"><i class="la la-plus-square"></i></a>
        </div>
    </div>
     @if($errors->has('fournisseur'))
        <span class="text-danger">{{ $errors->first('fournisseur') }}</span>
    @endif
</div>

What is the right syntax to use the old() function in the jQuery script?

1 Answers

The syntax of using old helper in laravel is like this:

{{ old('field_name') }}

this will print it as a string to the HTML page, so if you want to use it in the script, you have to parse it somehow.

but as far as I know, this only will work if the error was a validation error, unless if you redirected the page after the error happened like this:

return redirect()->back()
   ->withInput($request->except('_token')) // or whatever, ->all() also works 
   ->withErrors($validationErrors)

but anyway the right syntax for using the old data in the script:


<script> 
  let oldData = JSON.parse('{{json_encode(old("field_name"))}}');
  // you can use it now, you have parsed the same object that u received in the backend
  ...
</script>
Related