在 Laravel 中刷新页面后保留下拉列表中的动态值

Posted

技术标签:

【中文标题】在 Laravel 中刷新页面后保留下拉列表中的动态值【英文标题】:Retain dynamic values from Dropdown list after page refresh in Laravel 【发布时间】:2021-02-04 00:47:01 【问题描述】:

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

我有一个表单,用户选择国家,然后出现状态,然后出现城市。由于我使用的是 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>

Ajax

<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后。 (验证开始,但州和城市没有旧值)

【问题讨论】:

您正在使用 onChange 事件,为此您还需要使用 onLoad 事件 @sta 你能举一些例子吗? 嗨,Skumar,我的回答最终对你有用吗? 我没试过。我现在正在这样做。 @JasonRoman 我试过你的方法,当它填充 State 相对于 (pre-selected) Country Name 城市列表还是空的 【参考方案1】:

您在提交带有页面重新加载的表单时缺少州/城市值,因为这些 &lt;select&gt; 字段在加载页面时被硬编码为 disabled/readonly,并且没有触发更改国家/地区选择的相应操作。您不仅可以在 Country 更改时触发 State/City AJAX 更新,还可以在页面加载时触发。您可能希望将更新逻辑移动到它自己的函数中,如下所示:

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

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

那么你需要在页面加载和选择国家时调用这个函数:

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

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

这将确保即使在表单出现错误并且页面重新加载时也能正确加载州/城市。这种方法的唯一问题是,如果您已经选择了州/城市选项,它们将不会被重新选择。

要解决这个问题,您可以尝试一些方法:

在提交带有国家/地区的表单时获取州/城市列表,然后像处理国家/地区一样在模板中填充列表,自动选择已选择的选项 或者您可以在页面加载时在 JavaScript 中添加选定的州/城市值,然后让您的 load/change 事件在通过 AJAX 重新填充后使用 JavaScript 将这些相应选项设置为 selected

【讨论】:

我试过这个方法,州和城市的动态值不会在重新加载时改变,即使在预选国家之后 我的意思是,即使预先选择了 CountryStateCity 值也是空的跨度> 在您尝试切换到我上面的方法后,您是否检查过是否在页面加载时调用了 AJAX? 是的。 ajax 请求被调用,但前提是我更改了 country (填充 state 下拉列表)或 state (填充 城市下拉) 我更新了我的答案,以便在页面加载时正确更新州/城市,检查一下

以上是关于在 Laravel 中刷新页面后保留下拉列表中的动态值的主要内容,如果未能解决你的问题,请参考以下文章

刷新后如何保持下拉选择

刷新页面时重置值

网页设计中选中下拉列表中选项后如何实现页面刷新?

从数据库中重新加载下拉列表的数据而不刷新整个页面

刷新后在标签中显示文本

如何在 laravel 5.2 中重新加载页面后保留 select2 值?