javascript - 设置下拉列表的选定值,其中使用 Jquery 动态附加下拉列表的选项

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

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

我正在使用 dependency Dropdown , 在哪里选择Dealer's Dropdown Customer's ListJquery 动态绑定(bind).

在根据 Dealer Value 编辑模式时,我正在调用 Document.Ready 中的函数通过从 Ajax 调用获取数据来附加客户列表。

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

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

这是在 document.ready 中调用的函数中列表的动态绑定(bind).

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")该值来自模型,它包含的值存在于 <option> 中然而即将到来的警报始终为空或空白。

编辑

enter image description here

最佳答案

这应该有效。

$(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' />

关于javascript - 设置下拉列表的选定值,其中使用 Jquery 动态附加下拉列表的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48057457/

相关文章:

javascript - 如何提交在引导模式窗口中动态加载的ajax表单帖子?

javascript - 如何刷新jquery对话框以供下次使用?

javascript - Meteor 后端管理界面 : are there any packages that make this easy, 是 Django 吗?

javascript - 一个 div 位于另一个 div 中,两者都可点击。当按下内部按钮时,外部按钮也会被触发

javascript - 具有 HOC 的命名导出

javascript - 如何使用 javascript 删除辅助谷歌日历

javascript - 尝试在前置元素:上添加点击事件

javascript - 有没有办法从同一个列表中检索项目并将它们注入(inject)不同的页面?

html - 如何使用html将文件上传到我的服务器

html - Play Framework : how to render static HTML pages with static js and css?