Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
Ajax & Laravel 8: select term + onchange event = show cost in input type number

I'm trying to dynamically change <input type="number" name="SLACost" readonly> based on <select name="SLATerm"> option

enter image description here

A table (in DB) that contains:

  • SLATerms.
  • SLACost.
  • SLADeduction

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda