繁体   English   中英

从动态创建的Select元素中选择一个选项值

[英]Select an option value from a dynamically created Select element

我想从动态创建的下拉列表中选择一个选项值。

下面的代码创建了元素,但是我正在努力使选择工作。

var counter = 0;
//options will contain a list of document types from the db
/*
 *  <option value='1'>one</option>
 *  <option value='2'>two</option>
 *  <option value='3'>three</option>
 */
var $options = $("#listDocumentTypes > option").clone();
$.each(JSON.parse(JSON.stringify(e[2])), function(i, item) {
      var $selectValue = $('<select class="select optionUpdate" id="ddlDocumentTypeID' + counter + '" name="ddlDocumentTypeID[]">').append($options);

        $tr = $('<tr>').append(
        $('<td>').text(item.DocumentLocation.split("/")[item.DocumentLocation.split("/").length - 1]),
        $('<td>').text(ite.FileSize),
        $('<td>').text(item.DocumentDescription),
        $('<td>').html($selectValue.prop('outerHTML')),
        $('<td>').html("<a href='javascript:void(0);' title='delete file' value='" + item.DocumentID + "'  class='btn btn-default txt-color-red deleteFile'><i class='fa fa-trash-o fa-lg'></i></a>"),
      );

      //selection is failing here
      $("#ddlDocumentTypeID" + counter + "").val(item.DocumentTypeID).attr("selected", "selected");
      counter++;
    }

有什么建议吗?

在对象$selectValue上设置值,然后附加整个对象,而不仅仅是outerHTML

它无法正常运行的原因是您尚未将该行添加到dom中,因此在该行中搜索将不会返回任何内容

$.each(JSON.parse(JSON.stringify(e[2])), function (i, item) {

        var $selectValue = $('<select class="select optionUpdate" id="ddlDocumentTypeID'+counter+'" name="ddlDocumentTypeID[]">')
         .append($options); 
         // set value here
         .val(item.DocumentTypeID)


        $tr = $('<tr>').append(
            $('<td>').text(item.DocumentLocation.split("/")[item.DocumentLocation.split("/").length-1]),
            $('<td>').text(ite.FileSize),
            $('<td>').text(item.DocumentDescription),
            // append whole object
            $('<td>').append($selectValue.),
            $('<td>').html("<a href='javascript:void(0);' title='delete file' value='"+item.DocumentID+"'  class='btn btn-default txt-color-red deleteFile'><i class='fa fa-trash-o fa-lg'></i></a>"),


        );


        counter++;
    }

解决了。

基本上在$ option上使用array.find并设置selected的属性

 var option =Array.from($options).find(x => x.getAttribute("value") == item.DocumentTypeID);
      option.setAttribute("selected","selected");

https://jsfiddle.net/Pfunzo/e57rdpng

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM