I'm trying to dynamically change <input type="number" name="SLACost" readonly> based on <select name="SLATerm"> option
A table (in DB) that contains:
that should be fetched in the "Add new KPI Invoice" form.
I created a function in the controller to fetch the data as json:
/**
** KPI API
**/
public function fetchSLA()
{
$kpiTerms = KPITerms::all();
return response()->json([
'SLATermData' => $kpiTerms, // SLATermData is the name that will be used in Ajax.
]);
}
created a url for ajax to fetch in the web.php as Route::get('kpi/fetch/sla', 'fetchSLA')->name('kpi.fetchSLA'); // The API for fetching SLA as json
Then went ahead and created the ajax request GET
function fetchSLA() {
$.ajax({
type: 'GET',
url: "/management/kpi/fetch/sla",
dataType: 'json',
success: function (response) {
// console.log(response.SLATermData);
$("select[name='SLATerm']").change(function() {
$("input[name='SLACost']").val(response.SLATermData);
});
}
});
}
Obviously, SLATermData will fetch the entire data as json and print it in the SLACost input, it shows as [onject object object]
I tried to do this:
$("select[name='SLATerm']").change(function() {
$("input[name='SLACost']").val(response.SLATermData.SLACost);
});
I thought that adding SLACost after response.SLATermData will do the trick.
What's missing here?
So I made an ajax request to both SLATerm and SLACost and looped through the requested data. Then I made an if statement within the loop to change the SLACost based on the SLATerm selected.
function fetchSLA() {
$.ajax({
type: 'GET',
url: "/management/kpi/fetch/sla",
dataType: 'json',
success: function (response) {
$.each(response.SLATermData, function (key, value) {
$("select[name='SLATerm']").change(function() {
if ( $("select[name='SLATerm']").val() == value.SLATerm ) {
$("input[name='SLACost']").val(value.SLACost);
}
});
});
}
});
}
And here is the Laravel controller for the API:
/**
** KPI API
**/
public function fetchSLA()
{
$kpiTerms = KPITerms::get(['SLATerm' => 'SLATerm', 'SLACost' => 'SLACost']);
return response()->json([
'SLATermData' => $kpiTerms, // SLATermData is the name that will be used in Ajax.
]);
}
Now That I got it working, I'm trying to figure out how to clean the code.
As CBroe mentioned in the comments:
you should rather change your API - requesting all the data over and over again
Which I am trying to do.