简体   繁体   中英

how to show new select input only when select specific option and when select another options don't show by jquery? laravel

i'm trying to show new select input contains (states) options, when user select specific option a (USA) country, and when select another country non (USA) don't show the states select options i want in this case still hidden.

Route

Route::get('/ajax-form', [AjaxController::class, 'index'])->name('ajax.index');
Route::get('/getState/{id}', [AjaxController::class, 'getState'])->name('ajax.state');

Controller

class AjaxController extends Controller
{
    public function index()
    {
        $countries['data'] = Country::orderby('name')
            ->select('id', 'name')
            ->get();

        return view('ajax.index', compact('countries'));
    }
    
    public function getState($countryId = 0)
    {
        $states['data'] = State::orderby('name')
            ->select('id', 'name')
            ->where('country_id', $countryId)
            ->get();

        return response()->json($states);
    }

Blade form with script:

@extends('layouts.app')
    
@section('form')
<form>
  <div class="form-row">
    <div class="form-group col-md-12">
      <label for="inputCountry">Country</label>
      <select class="country" id="inputCountry" class="form-control">
        <option selected>Choose...</option>
        @if ($countries['data'] && $countries['data']->count() > 0)
          @foreach ($countries['data'] as $country)
            <option value="{{ $country->id }}">{{ $country->name }}</option>
          @endforeach
        @endif
      </select>
    </div>
  </div>
  <div id="stateShow" class="form-row hidden">
    <div class="form-group col-md-6">
      <label for="inputState">State</label>
      <select id="inputState" class="form-control">
        <option value='0' selected>Choose...</option>
      </select>
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Save</button>
</form>
@stop

@section('script')
<script type="text/javascript">
  $(document).ready(function () {
    $('#inputCountry').change(function() {
      var id = $(this).val();
      // Empty the States dropdown without first
      $('#stateShow').show();
      $('#inputState').find('option').not(':first').remove();
      // ajax request
      $.ajax({
        url: 'getState/' + id,
        type:'get',
        dataType: 'json',
        success: function(response) {
          var len = 0;
          if(response['data'] != null) {
            len = response['data'].length;
          }
          if(len > 0) {
            // Read data in the state option that related with country
            for(var i = 0; i < len; i++) {
              var id = response['data'][i].id;
              var name = response['data'][i].name;
              var option = "<option value='" + id + "'>" + name + "</option>";
              $('#inputState').append(option);
            }
          }
        }
      });
    });
  });
</script>
@stop

the above script doing, when i select any country, the hidden (states) select is shown, i want it shows only when i select (USA) and non that still hidden

could you help me

In your inputCountry select-box i am assuming {{ $country->name }} is country name so you can use $(this).find("option:selected").text() to get this value and then compare it with USA if they are equal show your div else hide it.

Demo Code :

 $('#inputCountry').change(function() { var id = $(this).val(); var text = $(this).find("option:selected").text().trim() //get text if (text == "USA") { $('#stateShow').show(); //show $('#inputState').find('option').not(':first').remove(); //your ajax call put here.... } else { $('#stateShow').hide(); //hide } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <form> <div class="form-row"> <div class="form-group col-md-12"> <label for="inputCountry">Country</label> <select class="country" id="inputCountry" class="form-control"> <option selected>Choose...</option> <option value="{{ $country->id }}">Abc</option> <option value="{{ $country->id }}">USA</option> </select> </div> </div> <div id="stateShow" class="form-row hidden"> <div class="form-group col-md-6"> <label for="inputState">State</label> <select id="inputState" class="form-control"> <option value='0' selected>Choose...</option> </select> </div> </div> <button type="submit" class="btn btn-primary">Save</button> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM