首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在动态添加的表行中创建级联下拉列表并保存到数据库中

如何在动态添加的表行中创建级联下拉列表并保存到数据库中
EN

Stack Overflow用户
提问于 2019-05-20 10:29:40
回答 1查看 379关注 0票数 0

我已经在表中添加了动态行,它们具有相互依赖的下拉列表(级联)。我可以成功地使用这些下拉列表添加动态行,但问题是如何根据第一个下拉列表(类别)中的选定值填充第二个下拉列表(子类别)的值?请看下图:https://imgur.com/sKQ304k

我已经可以填充第一个下拉列表中的值,它具有来自数据库的值,但我仍然在寻找如何填充第二个下拉列表中的值的方法。我尝试使用硬编码的值填充数据(参见下面的代码),它运行正常。但是,当我在数据库中获取这些值时,这就是我在苦苦挣扎的地方。

控制器

代码语言:javascript
复制
 //To populate data in second dropdown list
 public ActionResult GetPSESubcategories(Guid pse_category_id)
    {
        List<SelectListItem> subCategories = new List<SelectListItem>();
        var subCategoryList = PopulateDropdown.GetPSESubcategory(pse_category_id);
        return Json(subCategoryList, JsonRequestBehavior.AllowGet);
    }

视图

代码语言:javascript
复制
<div class="row" style="display:none;" id="patientExperienceDiv">
    <div class="table-responsive" style="padding-left:8px !important;">
        <table class="table">
            <thead>
               <tr>
                 <th style="border-bottom:none !important;border-top:none !important;">
                    <text style="font-weight:500 !important;"><strong>II.</strong>&nbsp;Categories</text><br />
                    <text style="font-size:12px;color:#a5a5a5;font-weight:400 !important;">Please select.</text>
                 </th>
                 <th style="border-bottom:none !important;border-top:none !important;">
                    <text style="font-weight:500 !important">Subcategories</text><br />
                    <text style="font-size:12px;color:#a5a5a5;font-weight:400 !important;">Please select.</text>
                 </th>
                 <th style="border-bottom:none !important;border-top:none !important;"></th>
                 <th style="border-bottom:none !important;border-top:none !important;"></th>
                 <th style="border-bottom:none !important;border-top:none !important;"></th>
               </tr>
             </thead>
             <tbody id="multipleCategoryTbl">
               <tr>
                 <td style="border-bottom:none !important;border-top:none !important;">
                     <div style="padding-top:2px">                                                            
                        @Html.DropDownListFor(a => a.addedCategory, new SelectList(ViewBag.PSECategories, "Value", "Text"), "Select Category", new { @class = "form-control", @id ="cat" })
                      </div>
                  </td>
                  <td style="border-bottom:none !important;border-top:none !important;">
                     <div style="padding-top:2px;">
                        @Html.DropDownListFor(a => a.addedSubcategory, new SelectList(ViewBag.PSESubcategories, "Value", "Text"), "Select Subcategory", new { @class = "form-control field", @disabled = "disabled", @id = "sub" })
                        @Html.EditorFor(a => a.addedSubcategory, new { htmlAttributes = new { @class = "form-control field", @readonly = "readonly", @id = "nature", @style = "display:none;" } })
                      </div>
                   </td>
                   <td style="border-bottom:none !important;border-top:none !important;">
                       <button type="button" class="form-control btn btn-default btn-sm" id="addNewCategoryBtn" style="text-align:center !important;">
                       <i class="fa fa-plus"></i>
                       </button>
                   </td>
                   <td style="border-bottom:none !important;border-top:none !important;">
                       <button type="button" class="form-control btn btn-default btn-sm" id="removeNewCategoryBtn" onclick="remove_row('multipleCategoryTbl')" style="text-align:center !important;">
                       <i class="fa fa-remove"></i>
                       </button>
                    </td>
                    <td style="border-bottom:none !important;border-top:none !important;"><input type="text" class="form-control" id="textId" name="ids" value="0" /></td>
                </tr>
             </tbody>
          </table>
</div>

JAVASCRIPT

代码语言:javascript
复制
<script>
   $(function () {
       $('#cat').change(function () {
           getSelectedItem(this, null);
       });

       $('#addNewCategoryBtn').click(function () {
           addRow('multipleCategoryTbl');
       });

       //sample hard-coded values that must be replaced by javascript on cascading dropdown list values from database
       var jsonObj = { "category1": ["subcat 1"], "category2": ["subcat 2.1", "subcat 2.2"], "category3": ["subcat 3.1", "subcat 3.2", "subcat 3.3"] };
       var keys = Object.keys(jsonObj);

       var category_dropdown = document.getElementById("cat");

       var getSelectedItem = function (element, row) {
           $("#sub").prop("disabled", false);

           var e = element;
           var selectedCategory = e.options[e.selectedIndex].value;
           alert(selectedCategory);    //selected value in the first dropdown list

           var sub_category_dropdown = (row != null ? row.getElementsByTagName("select")[1] : document.getElementById("sub"));

          alert(sub_category_dropdown.nodeValue); //check the values of second dropdown list

          sub_category_dropdown.options.length = 0;

          for (var i = 0; i < jsonObj[selectedCategory].length; i++) {                                                
             sub_category_dropdown[sub_category_dropdown.length] = new Option(jsonObj[selectedCategory][i], jsonObj[selectedCategory][i]);
          }
        };

        //to dynamically add table rows
        var addRow = function (tableID) {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var colCount = table.rows[0].cells.length;

        for (var i = 0; i < colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[0].cells[i].innerHTML;

            newcell.childNodes[0].selectedIndex = 0;
        }
        var selects = row.getElementsByTagName("select");
        selects[0].addEventListener('change', function () { getSelectedItem(this, row) }, false);
        };

        //this must be the place where the values of second dropdown is populated
        for (var keys in jsonObj) {                                     
        category_dropdown[category_dropdown.length] = new Option(keys, keys);
        }
   });

这是我为级联下拉列表创建的单独的javascript,但我不知道将其插入getSelectedItem函数的什么位置

代码语言:javascript
复制
$("#cat").on('change', function () {
        alert($(this).val());

        $("#sub").prop("disabled", false);
        $("#sub").empty();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetPSESubcategories", "PSERegistry")',
            dataType: 'json',
            data: { pse_category_id: $(this).val() },
            success: function (subCategories) {
                $("#sub").append($('<option></option>').val('').text('Select Subcategory'));
                $.each(subCategories, function (i, sub) {
                    $("#sub").append('<option value ="' + sub.Value + '">' + sub.Text + '</option>');
                });

                //Update the data in subcategory dropdown upon selection of category
                $("#sub").trigger("chosen:updated");
                $("#sub").trigger("liszt:updated");
            },
            error: function () {
                alert('Please select Category.');
            }
        });
        return false;
    });

更新:

我修改了javascript for cascading下拉列表,这是我拥有的,

代码语言:javascript
复制
<script>

    $('#cat').change(function () {
        alert('test');
        getSelectedItem(this, null);
    });

    var category_dropdown = document.getElementById("cat");

    function getSelectedItem(element, row) {
        $("#sub").prop('disabled', false);
        $("#sub").empty();                                   

        var e = element;
        var selectedCategory = e.options[e.selectedIndex].value;
        alert(selectedCategory);

        $.ajax({
             type: 'POST',
             url: '@Url.Action("GetPSESubcategories", "PSERegistry")',
             dataType: 'json',
             data: { pse_category_id: selectedCategory },
             success: function (subCategories) {

                 var sub_category_dropdown = (row != null ? row.getElementsByTagName("select")[1] : document.getElementById("sub"));
                 sub_category_dropdown.options.length = 0;

                 $("#sub").append($('<option></option>').val('').text('Select Subcategory'));
                 $.each(subCategories, function (i, sub) {

                 sub_category_dropdown[sub_category_dropdown.length] = new Option(sub.Text, sub.Value);
                                                //alert(sub.Value);
                 });
              },
              error: function () {
                 alert('Please select Category.');
              }
           });
         };

         function addRow(table_id) {
            alert('new row added');

            var table = document.getElementById(table_id);

            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);

            var colCount = table.rows[0].cells.length;
            alert(rowCount);

            for (var i = 0; i < colCount; i++) {

                var newcell = row.insertCell(i);

                newcell.innerHTML = table.rows[0].cells[i].innerHTML;
                //alert(newcell.innerHTML);
                //alert(newcell.childNodes[0].type);

                switch (newcell.childNodes[0].type) {
                    case "text":
                        newcell.childNodes[0].value = rowCount;
                    case "checkbox":
                        newcell.childNodes[0].checked = false;
                        break;
                    case "select":
                        newcell.childNodes[0].selectedIndex = 0;
                        break;
                }
             }

             var selects = row.getElementsByTagName("select");
             selects[0].addEventListener('change', function () {
                 alert('clicked');
                 getSelectedItem(this, row)
             }, false);
          }

动态添加行中的级联下拉列表已经在运行,但每当我在其他行的其他下拉列表上选择时,第一行(动态添加时要复制的原始行)会受到影响。

有人能帮我一下吗?提前谢谢你。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-24 08:29:26

我已经找到了解决我问题的办法。这就是我所做的,

视图

代码语言:javascript
复制
<div class="row" style="display:none;" id="patientExperienceDiv">
    <div class="table-responsive" style="padding-left:8px !important;">
        <table class="table" id="pxeTable">
           <thead>
              <tr>
                <th style="border-bottom:none !important;border-top:none !important;">
                   <text style="font-weight:500 !important;"><strong>II.</strong>&nbsp;Categories</text><br />
                   <text style="font-size:12px;color:#a5a5a5;font-weight:400 !important;">Please select.</text>
                </th>
                <th style="border-bottom:none !important;border-top:none !important;">
                    <text style="font-weight:500 !important">Subcategories</text><br />
                    <text style="font-size:12px;color:#a5a5a5;font-weight:400 !important;">Please select.</text>
                 </th>
                 <th style="border-bottom:none !important;border-top:none !important;"></th>
                 <th style="border-bottom:none !important;border-top:none !important;"></th>
                 <th style="border-bottom:none !important;border-top:none !important;"></th>
                 <th style="border-bottom:none !important;border-top:none !important;"></th>
                 </tr>
            </thead>
            <tbody id="pxeTbody">
                 <tr>
                    <td style="border-bottom:none !important;border-top:none !important;">
                       @Html.DropDownListFor(a => a.pxeAddedCategory, new SelectList(ViewBag.PSECategories, "Value", "Text"), "Select Category", new { @class = "form-control pxeCategoryDDL", @id = "pxeCategoryList" })
                    </td>
                    <td style="border-bottom:none !important;border-top:none !important;">
                        @Html.DropDownListFor(a => a.pxeAddedSubcategory, new SelectList(ViewBag.PSESubcategories, "Value", "Text"), "Select Subcategory", new { @class = "form-control pxeSubcategoryDDL", @id = "pxeSubcategoryList" })
                    </td>
                    <td style="border-bottom:none !important;border-top:none !important;">
                       <input type="text" class="form-control pxeRowIndex" id="pxeIndexId" name="pxeRowIndexIds" value="0" readonly />
                    </td>
                    <td style="border-bottom:none !important;border-top:none !important">
                       <input type="text" class="form-control pxeConcatField" name="pxeRowConcatField" readonly />
                    </td>
                    <td style="border-bottom:none !important;border-top:none !important;">
                       <button type="button" id="addNewCategoryBtn" class="form-control btn btn-xs btn-default addNewCategory" onclick="addRowPXE('pxeTbody')" data-toggle="tooltip" title="Add">
                       <i class="fa fa-plus"></i>
                       </button>
                    </td>
                    <td style="border-bottom:none !important;border-top:none !important;display:none;">
                        <button type="button" id="removeNewCategoryBtn" class="form-control btn btn-xs btn-default removeNewCategory" data-toggle="tooltip" title="Remove">
                        <i class="fa fa-remove"></i>
                        </button>
                    </td>
                 </tr>
              </tbody>
          </table>
      </div>
  </div>

JAVASCRIPT

代码语言:javascript
复制
<script>
   //cascading dropdown list inside dynamically added rows
   $("#pxeTable").on('change', '.pxeCategoryDDL', function () {
       var table = document.getElementById('pxeTbody');
       var rowCount = table.rows.length;

       var pxeSelectedCategory = $(this).val();
       var row = $(this).closest('tr');                            // get the row
       var pxeSubcatSelect = row.find('.pxeSubcategoryDDL');       // get the other select in the same row
       var pxeRowIndex = row.find('.pxeRowIndex');

       alert(rowCount);
       alert(pxeSelectedCategory);
       //alert(pxeSubcatSelect.innerHTML);

       //pxeSubcatSelect.attr('disabled', false);
       pxeSubcatSelect.empty();
       pxeRowIndex.val(rowCount);

       // make ajax call passing the pxeSelectedCategory to controller. And in the success callback, update the options of pxeSubcatSelect
       $.ajax({
           type: 'POST',
           url: '@Url.Action("GetPSESubcategories", "PSERegistry")',
           dataType: 'json',
           data: { pse_category_id: pxeSelectedCategory },
           success: function (subCategories) {
               pxeSubcatSelect.append($('<option></option>').val('').text('Select Subcategory'));
               $.each(subCategories, function (i, sub) {
                   pxeSubcatSelect.append('<option value ="' + sub.Value + '">' + sub.Text + '</option>');
              })
           }
        });
        return false;
     });

     //sub category dropdown on change
     $("#pxeTable").on('change', '.pxeSubcategoryDDL', function () {
         var table = document.getElementById('pxeTbody');
         var rowCount = table.rows.length;
         var row = $(this).closest('tr');

         //get the selected values in each dropdown list
         var pxeCategory = row.find('.pxeCategoryDDL').val();
         var pxeSubcategory = row.find('.pxeSubcategoryDDL').val();
         var pxeRowIndex = row.find('.pxeRowIndex').val();
         var pxeConcatField = row.find('.pxeConcatField');

         //concatenate all values and store in hidden text field
         var pxeConcatData = pxeCategory + "," + pxeSubcategory + "," + pxeRowIndex;
         alert(pxeConcatData);
         pxeConcatField.val(pxeConcatData);
      });


      //remove added rows
      $(document).on("click", ".removeNewCategory", function ()     {                                      
          $(this).closest("tr").remove(); // closest used to remove the respective 'tr' in which I have my controls
      });


      //dynamically add row for multiple events
      function addRowPXE(table_id) {
        alert('new pxe row added');
        var table = document.getElementById(table_id);
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var colCount = table.rows[0].cells.length;
        alert(rowCount);

        $("#removeNewCategoryBtn").attr('display', 'block');

        for (var i = 0; i < colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[0].cells[i].innerHTML;
            newcell.childNodes[0].selectedIndex = 0;

            switch (newcell.childNodes[0].type) {
               case "text":
                   newcell.childNodes[0].value = rowCount;
                   break;
               case "select":
                   newcell.childNodes[0].selectedIndex = 0;
                   break;
             }
           }
        };
    </script>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56213666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档