In my Laravel project I have an appointment form where patient can choose a doctor after choosing a branch from the dropdown list. I use AJAX for doing the functionality.
Now after any validation failed all the form value restored accept the doctor.
But I want to automatically restored that selected doctor after validation failed.
html form
<select class="form-control appointment_form_searchField" id="appointment_branch" name="appointment_branch" style="font-size:.7em;;width: 100%;">
<option value="">Select Branch</option>
@if($_SESSION['branch'] != null)
@foreach($_SESSION['branch'] as $data)
<option value="{{ $data->id }}">{{ $data->name }}</option>
@endforeach
@endif
</select>
<select class="form-control" id="appointment_doctor" name="appointment_doctor" style="font-size:.7em;padding: 0.6500rem .75rem;width: 100%;">
<option value="">Select Doctor</option>
</select>
AJAX
jQuery(".appointment_form_searchField").change(function() {
var branch_id = $("#appointment_branch").val();
var token = $('input[name=_token]').val();
if(branch_id.trim() != '')
{
jQuery.ajax({
url:"{{ url('/filter_doctor') }}",
type: 'GET',
data: {_token :token, branch_id : branch_id},
success:function(msg){
$('#appointment_doctor option').remove();
trHTML = '';
trHTML += "<option value=''>Select Doctor</option>";
msg.forEach(function(item){
trHTML += "<option value='"+item.id+"'>" + inputem.name + "</option>";
});
$('#appointment_doctor').append(trHTML);
}
});
}
});
controller
public function filter_doctor(Request $request)
{
$branch_id = $request->branch_id;
$query = DB::table('service_doctors');
$query->select('doctor_id','inactive_dates_in_this_month');
if($branch_id != '0')
$query->where('branch_id','=', $branch_id);
$result_time = $query->get();
$array_doctor_id = $result_time->pluck('doctor_id');
$doctor = Doctor::whereIn('id', $array_doctor_id)->get();
return $doctor;
}
Anybody Help please ? Thanks in advance
If you are using Laravel 5 then you can do something like this.
In your form add missing details appointment_branch and appointment_doctor like below.
The
Request::old()
option load previous posted value in from hence you need to first select old value forappointment_branch'. Also temporary store
old appointment_doctorvalue in
data-oldid` so the script can identify which was the old value submitted by user and can load this select box when document is ready.And then write your script like below.