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

150
Visualizações
Problem selecting an item after building the select options with AJAX

I use this javascript to select a specific option (the option value being specified within a hidden element):

$("select").each(function() {
    var id = $(this).attr('id');
    var source = 'input:hidden[name=select_'+id+']';
    if ($(source).length) {
        var selected = $(source).val();
        $(this).val(selected).change();
    }
});

This works fine when the options are hard coded in the HTML source.

I now need to populate the options with an AJAX call, I use the below method:

select : function(ctrl,id) {
    var call = '/'+ctrl+'/'+$("#auth input[name=verify]").val();
    $.getJSON(call, function(result) {
        $.each(result, function() {
            $('#'+id).append($("<option />").val(this.id).text(this.title));
        });
    });
},

I process the select method (AJAX) on page load, and the options populate fine. But when I then try to select the desired option, the browser defaults to the first option.

I have tested what is happening by sticking some alerts around the code as thus:

    alert($(this).val(selected));       // A
    alert($(this).val());               // B
    $(this).val(selected).change();
    alert($(this).val());               // C

When the options are hard coded I get A=3, B=null, C=3 i.e. it works When the options are populated via AJAX I get A=3, B=null, C=null i.e. it fails

I am guessing that I need to trigger some kind of change() event after populating the option list with AJAX. I have tried (a bit overkill I know):

$('#'+id).append($("<option />").val(this.id).text(this.title).change());

&

$('#'+id).append($("<option />").val(this.id).text(this.title)).change();

Any ideas? Thx

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

0

Problem solved.

Although I was triggering the code in the correct order (in theory), because of javascripts event driven behaviour the AJAX call was not completing until after my select initialisation had finished. So I moved the code to set the selected option into the AJAX call and voila.

select : function(ctrl,id) {
var call = '/'+ctrl+'/'+$("#auth input[name=verify]").val();
$.getJSON(call, function(result) {
    $.each(result, function() {
        $('#'+id).append($("<option />").val(this.id).text(this.title));
    });
    var source = 'input:hidden[name=select_'+id+']';
    if ($(source).length) {
        var selected = $(source).val();
        $('#'+id).val(selected).change();
    }
});
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