首页 > 解决方案 > 在 Laravel 中刷新页面后保留下拉列表中的动态值

问题描述

PS-关于同一个问题还有其他一些答案,但对我来说不是很清楚

我有一个表单,用户选择国家,然后出现状态,然后出现城市。由于我使用的是 Laravel 表单验证,因此提交。如果有任何错误,则刷新页面,然后错误消息显示在相应的输入字段下。但是,每次页面刷新时(由于一些错误),State 和 City 下拉列表中的值都会消失。我想保留这些价值观。我该怎么做?

这是我的代码

   <!DOCTYPE html>
<html lang="en">
 <head>
   <!-- Required meta tags -->
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

   <!-- Bootstrap CSS -->
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">


   <!-- Optional JavaScript -->
   <!-- jQuery first, then Popper.js, then Bootstrap JS -->
   <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
   <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
   <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
   <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

   <!-- Sweet Alert -->
   <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

   </head>
 <body>
   @if(!(Auth::check()))
   <!-- Navigation Bar -->
  <div class="container-fluid">
 <nav class="navbar navbar-expand-md navbar-dark bg-info">
   <a class="navbar-brand" href="#">Navbar</a>
   <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
       <span class="navbar-toggler-icon"></span>
   </button>
   <div class="collapse navbar-collapse" id="navbarNav">
       <ul class="navbar-nav mr-auto">
           <li class="nav-item active">
               <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
           </li>
           <li class="nav-item">
               <a class="nav-link" href="#">Features</a>
           </li>
           <li class="nav-item">
               <a class="nav-link" href="#">About Us</a>
           </li>
           <li class="nav-item">
               <a class="nav-link" href="contact">Contact Us</a>
           </li>
       </ul>
       <ul class="navbar-nav">
           <li class="nav-item">
               <a class="nav-link" href="login">Login</a>
           </li>
           <li class="nav-item">
               <a class="nav-link"href="new_user">Signup</a>
           </li>
       </ul>
   </div>
</nav>

<div class="container pt-2">
<div class="row shadow p-3 mb-5 bg-info rounded text-center text-white">
 <div class="col ">
 
   <h2>New User Registration</h2>
 </div>
   </div>
 </div>

<div class="row  m-5 p-5 bg-light  text-info">
    <div class="col">


 <form class="form-group" method="post" action="recheck_form" autocomplete="off">

<div class="form-group {{ $errors->first('first_name') ? ' has-error' : 'has-success' }}">
 @csrf
<label for="fname">First Name:</label>
 <input type="text" class="form-control" name="first_name" value="{{ old('first_name') }}">
 <small class="text-danger">{{$errors->first('first_name') }}</small>
 
</div>


<div class="form-group {{ $errors->first('last_name') ? ' has-error' : 'has-success' }}">
<label for="lname">Last Name:</label>
 <input type="text" class="form-control" name="last_name" value="{{ old('last_name') }}">
 <small class="text-danger">{{ $errors->first('last_name') }}</small>
</div>


<div class="form-group {{ $errors->first('email') ? ' has-error' : 'has-success' }}">
<label for="email">Email/Username:</label>
 <input type="text" class="form-control" name="email" value="{{ old('email') }}">
 <small class="text-danger">{{ $errors->first('email') }}</small>
</div>

<div class="form-group {{ $errors->first('password') ? ' has-error' : 'has-success' }}">
 <label for="pwd">Password:</label>
 <input type="password" class="form-control" name="password" >
 <small class="text-danger">{{$errors->first('password') }}</small>
</div>


<div class="form-group {{ $errors->first('confirm_password') ? ' has-error' : 'has-success' }}">
 <label for="confpwd">Confirm Password:</label>
 <input type="password" class="form-control" name="confirm_password" >
 <small class="text-danger">{{ $errors->first('confirm_password') }}</small>
</div>


 <div class="form-group {{ $errors->first('mobno') ? ' has-error' : 'has-success' }}">
<label for="mobno">Mobile Number:</label>
 <input type="text" class="form-control" name="mobno" value="{{ old('mobno') }}">
 <small class="text-danger">{{ $errors->first('mobno') }}</small>
</div>


<div class="form-group {{ $errors->first('dob') ? ' has-error' : '' }}">
<label for="dob">Date of Birth(in YYYY-MM-DD):</label>
 <input type="text" class="form-control" name="dob" value="{{ old('dob') }}">
 <small class="text-danger">{{ $errors->first('dob') }}</small>
</div>


<div class="form-group {{ $errors->first('gender') ? ' has-error' : '' }}">
 <label for="gender">Gender:</label>

 <br>
 &nbsp;&nbsp;&nbsp;&nbsp;
 <input class="form-check-input" type="radio" name="gender" id="Female" value="Female" {{old('gender')=="Female" ? 'checked': ""}}>
 <label class="form-check-label" for="Female">
   Female
 </label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

 <input class="form-check-input" type="radio" name="gender" id="Male" value="Male"  {{old('gender')=="Male" ? 'checked': ""}}>
 <label class="form-check-label" for="Male">
   Male
 </label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

 <input class="form-check-input " type="radio" name="gender" id="Other" value="Other"  {{old('gender')=="Other"?'checked':""}}>
 <label class="form-check-label" for="Other">
   Other
 </label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
 <small class="text-danger">{{ $errors->first('gender') }}</small>
</div>


 <div class="form-group {{$errors->first('address') ? ' has-error' : '' }}">
 <label for="address">Address:</label>
 <textarea class="form-control" rows="2" name="address">{{ old('address') }}</textarea>
 <small class="text-danger">{{ $errors->first('address') }}</small>
</div>


<div class="form-group {{ $errors->first('country') ? ' has-error' : '' }}">
<label for="country">Country:</label>
<select name="country" class="form-control" id="countrylist">
      <option disabled selected>Select Country</option>
      
      @foreach($countryname as $key => $country)
       <option id="countryname" value="{{$country->countryname}}" {{old('country')==$country->countryname ?'selected' :''}}>{{$country->countryname}}</option>
       
        @endforeach
     </select>
   <small class="text-danger">{{ $errors->first('country') }}</small>
   </div>

  <div class="form-group {{$errors->first('state') ? ' has-error' : '' }}" id="statelistdiv">
   <label>State:</label><br /> 
   <select name="state" id="statelist" class="form-control demoInputBox">
      <option readonly disabled>Select State</option>
    
    </select>
<small class="text-danger">{{ $errors->first('state') }}</small>
</div>

 <div class="form-group {{$errors->first('city') ? ' has-error' : '' }}" id="citylistdiv">
     <label>City:</label><br /> 
     <select name="city" id="citylist" class="form-control demoInputBox">
         <option readonly disabled>Select City</option>
       </select>
   <small class="text-danger">{{ $errors->first('city') }}</small>
 </div>

<div class="form-group {{ $errors->first('pincode') ? ' has-error' : 'has-success' }}" >
 <label for="pincode">Pin Code:</label>
 <input type="text" class="form-control" name="pincode"  value="{{ old('pincode') }}" id="pincode">
 <small class="text-danger">{{$errors->first('pincode')}}</small>
</div>


<div class="form-group">
 <label for="dt">Date and Time of Submission:</label>
 <input type="text" class="form-control" name="dt" readonly value=@php date_default_timezone_set("Asia/Kolkata"); echo date("Y-m-d,H:i:s ") @endphp>
</div>


<div class="form-group text-center">
<input type="submit" id="send_form" class="btn btn-primary mb-2"><br>
<a href="login">Already Signed up? Login Here</a>
</div>

<script>
//SCRIPT GOES HERE.SEE AJAX PART FOR THE SCRIPT
<script>

</form>
</div>
</div>
</div>



@else

<script>window.location = "dashboard";</script>
@endif




</body>
</html>

阿贾克斯

<script type="text/javascript">

 $(document).ready(function(){
   $(function(){
     viewStateList();
     viewCityList();
    });
   
 //     $('#statelistdiv').hide();
 // $('#citylistdiv').hide();
 // $('#pincode').hide();

  
function viewStateList(){
 var countryname = $('#countrylist').val();
 
     console.log("State Name for Country",countryname);

       if(!countryname){
         return;
       }
       $.ajaxSetup({
           headers: {
               'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
           }
           });  
                $.ajax({
                       type:'GET',
                       url: 'get-states?countryname='+countryname,
                       success:function(response){
                         // console.log(response);
                         if(response){
                            // $('#statelistdiv').show();
                           $("#statelist").empty();
                           // If no State exists for a country
                           if(response.length==0){
                               $('#statelist').append('<option value="Unnamed State in '+countryname+'">Unnamed State in '+countryname+'</option>');
                             }
                            
                            // $("#statelist").append('<option>Select State</option>');
                            $.each(response,function(key,value){
                             console.log("States-> ",value);
                               $("#statelist").append('<option value="'+value+'">'+value+'</option>');
                             
                              
                               });
                         }

                      },
        

                }); //ajax ends

 
} //viewStateList ends

function viewCityList(){
var statename = $('#statelist').val();
  console.log("City Name for state",statename);
       if(!statename){
         return;
       }
        $.ajaxSetup({
           headers: {
               'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
           }
           });  
       $.ajax({
                 type:'GET',
                 url: 'get-cities?statename='+statename,

                 success:function(response){
                   // console.log(response);

                   if(response){                  
                     // $('#citylistdiv').show();
                     $("#citylist").empty();
                      // $("#citylist").append('<option>Select City</option>');
                      if(response.length==0){
                       $('#citylist').append('<option value="Unnamed City in '+statename+'">Unnamed City in '+statename+'</option>');
                     }
                    
                      $.each(response,function(key,value){
                       console.log("Cities-> ",value);
                       
                         $("#citylist").append('<option value="'+value+'">'+value+'</option>');
                       
                         
                             // $('#pincode').show();
                     });
                   }
                     // $('#pincode').show();
                 },

   

          }); //ajax ends


} //viewCityList ends

$('#countrylist').change(viewStateList);
   

$('#statelist').change(viewCityList);

     


      


 

}); //ready fn ends
</script>


一些图片

选择 国家城市(在提交表单之前)

在此处输入图像描述

点击后Submit。(验证开始,但州和城市没有旧值)

在此处输入图像描述

标签: jqueryajaxlaravelforms

解决方案


You are missing State/City values upon submitting the form with a page reload because those <select> fields are hardcoded as disabled/readonly upon loading the page, and there is no corresponding action that triggers a change to the Country select. You can trigger the State/City AJAX update not only when Country changes, but when the page loads. You would want to move your update logic into its own function, like so:

function countrySelected() {
  var countryname = $('#countrylist').val();
  if (!countryname) {
    return;
  }

  // update state and city here
  $.ajaxSetup({/* ... */});
  $.ajax({/* ... */});
}

Then you need to call this function both when the page loads, and when a Country is selected:

// update when country selected
$('#countrylist').on('change', countrySelected);

// update when page has loaded
$(function() {
  countrySelected();
});

This will make sure State/City are loaded properly even when the form has errors and the page reloads. The only issue with this approach is that if you already had State/City options selected, they will not be re-selected.

To fix that you could try a few things:

  • get the list of states/cities when submitting the form with a country, and then populate the lists in your template just like you do with countries, auto-selecting the option that was already selected
  • or you could add selected state/city values in JavaScript on page load and then have your load/change event use JavaScript to set those corresponding options to selected after re-populating via AJAX.

推荐阅读