There are times when you want to let the users of your site to add their own records in the dropdown. You can have another menu for adding items specific to that dropdown. But what if you have plenty of inputs and you came up with that dropdown and realizes that you haven't added the option you want to select. Well you can add it on that separate page but you have to re-type all those things you already encoded. Well that's kind of tedious to do.use App\WaterSource;
Route::get('/profiles/create/waterSource',function(){
$data = WaterSource::orderBy('description')->get();
return Response::json($data);
});
<div class="form-group">
<label>State
<select name="waterSource" id="WaterSource" class="form-control input-sm">
<option value=""></option>
@foreach($waterSources as $waterSource)
<option value="{{ $waterSource->id }}">{{ $waterSource->name}}</option>
@endforeach
</select>
</label>
</div>
<a href="#" class="small" data-toggle="modal" tabindex="-1" data-target=".modal-illness"> Add</a>
<div class="modal fade modal-waterSource" id="myModal-waterSource" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add New Water Source</h4>
</div>
<div class="modal-body">
{!! Form::open(['url' => 'water_sources','class'=>'myForm-waterSource']) !!}
<div class="form-group">
{!! Form::text('description',null,['class'=>'input form-control','id'=>'modal-waterSource','autofocus'=>'autofocus']) !!}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
{!! Form::submit('Submit',['class'=>'btn btn-primary btn-sm']) !!}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
<script>
$(document).on('submit', '.myForm-waterSource', function(e) {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(html) {
$.get('{{ url('profiles') }}/create/waterSource', function(data) {
console.log(data);
$.each(data, function(index,subCatObj){
if (!$('#waterSource option[value="'+subCatObj.id+'"]').length) {
$('#waterSource').append('<option value="'+subCatObj.id+'">'+subCatObj.description+'</option>');
}
});
$('#myModal-waterSource').modal('hide');
$('#modal-waterSource').val('');
});
}
});
e.preventDefault();
});
</script>
Labels: Laravel