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>
<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>
<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>
<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> <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)
After clicking Submit. (The validation kicks in, but the State and city don't have their old values)

