【问题标题】:Setting selected value of Dropdown List where the Options of Dropdown List are appended dynamically using Jquery设置下拉列表的选定值,其中下拉列表的选项使用 Jquery 动态附加
【发布时间】:2018-01-02 17:59:57
【问题描述】:

如果有人有解决方案,请帮助。

我正在使用dependency Dropdown,其中Dealer's Dropdown 的选择Customer's ListJquery 动态绑定。

根据经销商价值在编辑模式下,我在 Document.Ready 中调用一个函数,该函数通过从 Ajax 调用中获取数据来附加客户列表。

此函数执行后,我从选项中设置选定的值,但它显示null/blank。尝试了许多解决方案。我在这个网站上提到了很多问题,但结果是一样的。我在哪里做错了吗?

<select id="ddlcustomerlstEdit" name="ddlcustomerlstEdit" class="form-control">
         <option value=""> -select Customer- </option>
</select>

这是在document.ready 中调用的函数中 List 的动态绑定。

if (data != "Blank") {
      $("#ddlcustomerlstEdit").html("");
           var str = '<option value=""> -Select Customer- </option>';
           for (var i = 0; i < data.length; i++) {
               str += '<option value=' + data[i].CustomerID + '> ' + data[i].CustomerName + '</option>';
           }
                        $("#ddlcustomerlstEdit").append(str);
}

只要这个函数执行,我就会设置选定的值。

var customerIdVal = $("#hdnCustomerID").val();
$('#ddlcustomerlstEdit option[value="' + customerIdVal+'"]').attr("selected", "true");
alert($("#ddlcustomerlstEdit").val());

$("#hdnCustomerID") 这个值来自模型,它包含的值存在于&lt;option&gt; 中,但即将到来的警报始终为空或空白。

编辑

【问题讨论】:

  • 发布data 中的数组。没有它,就很难找到缺少的东西。
  • 还有你的hdnCustomerID隐藏元素在哪里?
  • 您可以看到编辑和隐藏元素包含用户先前选择的值,在这种情况下为2。我正在使用它在选项中进行比较,然后相应地使该选项成为选中状态。 @AnkitAgarwal
  • 检查答案,如果我理解你的正确与否,请告诉我
  • 是的,您理解正确,但我收到的警报是空白的,您所做的没有任何区别。那我错在哪里了?

标签: javascript jquery html asp.net-mvc html-select


【解决方案1】:

这应该可以工作。

$(document).ready(function() {
  var data = [{
    'CustomerID': '2',
    'CustomerName': 'Test55'
  }];
  if (data != "Blank") {
    $("#ddlcustomerlstEdit").html("");
    var str = '<option value=""> -Select Customer- </option>';
    for (var i = 0; i < data.length; i++) {
      str += '<option value=' + data[i].CustomerID + '> ' + data[i].CustomerName + '</option>';
    }
    $("#ddlcustomerlstEdit").append(str);

    var customerIdVal = $("#hdnCustomerID").val();
    $('#ddlcustomerlstEdit option[value="' + customerIdVal + '"]').attr("selected", "true");
    alert($("#ddlcustomerlstEdit").val());
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlcustomerlstEdit" name="ddlcustomerlstEdit" class="form-control">
         <option value=""> -select Customer- </option>
</select>

<input type='hidden' value='2' id='hdnCustomerID' />

【讨论】:

  • 你能解释一下你的代码和我的代码有什么不同吗?因为我的仍然返回空白值。 @AnkitAgarwal
  • 您是否包含了 JQuery?在代码中添加debugger 并使用chrome 开发者控制台进行调试。这应该对你有帮助
  • 您找到问题所在了吗?
  • 您在数组中添加的数据来自我的 ajax 调用。并且当我试图在执行函数后立即设置选择值时,它首先设置它,然后附加选项,因为它在后台异步运行。我将async 设置为 false,然后它按照我的要求进入流程。
  • 太棒了。如果对您有帮助,可以将其标记为绿色
猜你喜欢
  • 2012-06-09
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 2015-07-06
  • 2017-06-17
相关资源
最近更新 更多