Iterated show/hide select options, on submit gives the last selected option

  css, html, javascript, jquery, laravel

I have this iterated show/hide select options, if I submit it and dd() the value, it gives the last selected option value. Any solutions??
These are my codes, working with Laravel 8.x

Controller, ServicesController

public function index()
{
    $category = Category::orderBy('name', 'asc')->get();
    $subcategory = Subcategory::orderBy('name', 'asc')->get();
    $region = Region::orderBy('name', 'asc')->get();
    $city = City::orderBy('name', 'asc')->get();
    return view('pages.post', compact('region','city','category','subcategory'));
}

My View, post.blade

<form method="POST" action="{{ route('post.store') }}">
                    @csrf
    <div class="form-group col-md-12">
                            <select id="q" name="region" class="form-control">
                                <option value="Empty" selected>-- Region --</option>
                                @foreach($region as $regions)
                                <option value="{{ $regions->id }}">{{ $regions->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div id="cityEmpty" class="form-group col-md-12 data">
                            <select class="form-control">
                                <option value="">-- City --</option>
                            </select>
                        </div>
                        @foreach($region as $regions)
                        <div id="city{{ $regions->id }}" class="form-group col-md-12 data">
                            <select name="city" class="form-control">
                                @foreach($city as $cities)
                                @if($cities->region_id == $regions->id)
                                <option value="{{ $cities->name }}">{{ $cities->name }}</option>
                                @endif
                                @endforeach
                            </select>
                        </div>
                        @endforeach
    <button type="submit" class="btn btn-primary btn-round btn-lg btn-block mb-3"><i class="now-ui-icons arrows-1_share-66"></i> Post</button>

                    </form>

My Script

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $("#q").on('change', function(){
      $(".data").hide();
      $("#city" + $(this).val()).show();
    }).change();
  });
</script>

Source: Ask Javascript Questions

LEAVE A COMMENT