首页 > 解决方案 > 我在 textarea 中显示列表框的选定项目,但是当我修改 textarea 值时,它停止工作

问题描述

我有下一个代码来显示文本区域中列表框的选定选项:

$(".listBoxClass").change(function () {
        var str = "";
        $("#listBoxID option:selected").each(function () {
            str = $(this).text() + " \n";
        });
        $("#textAreaID").append(str);
    }).trigger("change");

它显然有效,但如果我删除一个单词,或在 textArea 中进行任何更改,代码将停止工作,所以如果我在 listBox 中选择其他项目,它不会出现在 textArea 中......我需要允许用户修改 textArea 值的选项,因此他也可以手动输入值

标签: javascriptrazorlistboxtextareaselecteditem

解决方案


您应该设置文本区域的值,而不是附加到它。而且您没有将它连接到字符串,而是在每次迭代中不断替换它。

$(".listBoxClass").change(function() {
  var str = "";
  $("#listBoxID option:selected").each(function() {
    str += $(this).text() + " \n"; //concat it, do not replace, note the +=
  });
  $("#textAreaID").val(str);  //replace tha value
}).trigger("change");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="multiple" class="listBoxClass" id="listBoxID">
  <option>One</option>
  <option>Two</option>
  <option>Three</option>
</select>
<textarea id="textAreaID"></textarea>


推荐阅读