在jQuery中加载下拉值后设置下拉选择值 [英] Set dropdown selected value after loading dropdown values in jQuery

查看:62
本文介绍了在jQuery中加载下拉值后设置下拉选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当下拉列表成功加载后,我正在尝试在下拉列表中设置选定的值.

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

在设置选定的值之后,我正在通过ajax或jQuery加载下拉列表,但是有时它可以正常工作,有时由于加载下拉列表的延迟,因此不会设置选定的值.我也尝试过setTimeout,如下所示,但无法正常工作:

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...

谢谢

推荐答案

在这里,您可以使用 setInterval 来继续检查元素是否已填充.第一个 setTimeout 函数只是模拟花费3秒的时间将选项添加到列表中.

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>

这篇关于在jQuery中加载下拉值后设置下拉选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆