Search code examples
javascriptjqueryajaxdrop-down-menuselected

Set dropdown selected value after loading dropdown values in jQuery


I am trying to set selected value in dropdown list when the dropdown is successfully loaded.

I am loading dropdown list vaues by ajax or jQuery after that set selected value but sometime it's working fine and sometime it will not set selected the value because delay of loading dropdown. I have also tried setTimeout for that as below but it's not working properly:

if($("#ddlToUnit").length>0)
{     
setTimeout($("#ddlToUnit option[value='"+data.Records.GxMovement.ToUnit_v+"']").attr("selected","selected"),1000);
}
else
{ 
$("#ddlToUnit option[value='"+data.Records.GxMovement.ToUnit_v+"']").attr("selected","selected");
}

I want to set selected value after loading the dropdownlist...

Thanks


Solution

  • Here's a way you can use setInterval to keep checking whether the elements have been populated yet. The first setTimeout function is just simulating taking 3 seconds to add an option to a list.

    setTimeout(function() {
      var newOption = document.createElement('option');
      newOption.innerHTML = 'Option Text';
      document.getElementById('list').appendChild(newOption);
    }, 3000);
    
    // Do something only after list is populated
    var interval = setInterval(function() {
      if (document.querySelectorAll('#list option').length > 0) {
        console.log('List is definitely populated!');
        clearInterval(interval);
      }
    }, 200);
    <select id="list">
    </select>