1

P.S- There are some other answers regarding the same question, but they are not very clear to me

I have a form where a user selects Country, then States appear, then City. Since I am using Laravel form validation, the submitted. If there is any error, the page is refreshed, then the error messages show up under the respective input fields. But, every time the page refreshes (due to some errors), the values in the dropdown list of State and City vanishes. I want to retain those values. How do I do it?

Here are my codes

Blade

   <!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/[email protected]/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>


Some images

Selecting Country, State and City (before form submission)

enter image description here

After clicking Submit. (The validation kicks in, but the State and city don't have their old values)

enter image description here

10
  • You are using onChange event, for this you need to use onLoad event also Commented Oct 21, 2020 at 6:44
  • @sta Can you give some examples? Commented Oct 21, 2020 at 6:59
  • Hi Skumar, did my answer end up working for you? Commented Oct 22, 2020 at 17:48
  • I didn't try it. I am doing that now. Commented Oct 23, 2020 at 4:42
  • @JasonRoman I tried your method, and while it is populating the State with respect to the (pre-selected) Country Name, the City list is still empty Commented Oct 23, 2020 at 5:26

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

5 Comments

I tried this method, the dymanic values of states and cities do not change on reload, even after the country is pre-selected
I mean, even if the Country is pre-selected, the State and City values are empty
After you tried switching to my method above, did you check to see if the AJAX is being called on page load?
Yes. ajax request is called, but only if I change the value of the country (to populate the state dropdown) or state (to populate the city dropdown)
I updated my answer so that state/city are updated properly on page load, check it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.