Reputation: 31
I'm new in laravel, i just want to ask if how can i fill another textbox when i select a data in a dropdown. In my table named 'booklist' i have this columns 'book_title' and 'type_id' which has a relationship with 'booktypes' table with columns, 'type_id' and 'book_types'
i want to show the book types based on what book title i select in my dropdown (e.g Geometry (title) Math (type))
now i can only show and select all the book types in my dropdown based on this codes
<div class="form-group">
<label>Select Book</label>
<select class="form-control" name="book_id">
<option value="">-----------</option>
@foreach ($booklist as $boo)
<option value="{{$boo->book_id}}">{{ $boo->book_title }}</option>
@endforeach
</select>
</div>
my ShelfController
public function addshelfa()
{
return view('addshelf.addtoshelfa',['booklist'=>Booklist::all()]);
}
if a select for example Geometry want to show its type in here:
<div class="form-group">
<label>Book Type</label>
<input value="" type="text" class="form-control" name="type_id" disabled>
</div>
Upvotes: 1
Views: 1347
Reputation: 3065
For achieve this kind of functionality you need to add ajax call, this is going to be a long answer. So, i make it step by step and this is a rough phototype.
step 1: Your ajax functionality part,
// meta tag add inside your html head
<meta name="csrf-token" content="{{ csrf_token() }}" />
// ajax header setup
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
/**
* change book action
*/
// you need to give id attribute to book_id field.
$(document).on('change', '#book_id', function (e) {
e.preventDefault();
var book_id = $('#book_id').val();
var route = "/book-type/set";
$.ajax({
type: 'POST',
url: route,
data: {
book_id: book_id
},
success: function (data) {
// you can check for status here
$("input[name=type_id]").val(data.book_type_id);
},
error: function(XMLHttpRequest) {
// toastr.error('Something Went Wrong !');
}
});
});
step 2: backend handle part
Define route for handle request,
Route::post('/book-type/set', 'YourController@bookTypeSet');
Define Your method,
public function bookTypeSet(Request $request)
{
// this is a rough prototype you need to give your actual data from here
$bookId = $request->get('book_id');
$book = Book::findOrFail($bookId);
$bookType = $book->bookTypes;
return response()->json(['book_type_id'=>$bookType->id, 'status'=>'200']);
}
Upvotes: 2