【问题标题】:I show the selected items of a listbox in a textarea, but when i modify the textarea value, it stops working我在 textarea 中显示列表框的选定项目,但是当我修改 textarea 值时,它停止工作
【发布时间】:2018-10-13 20:00:19
【问题描述】:

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

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

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

【问题讨论】:

  • 如果您能准确解释“停止工作”的含义,将会很有帮助。开发者控制台是否报告错误?有任何事情发生吗?
  • 你可以添加你的html吗?
  • 为什么要附加到文本区域?它是一个实际的
  • 请添加缺少的 HTML,不是实现 HTML 的代码,而是实际呈现的 HTML,因为很难从您的代码中得出它的样子。
  • 这里是html代码:
    @Html.ListBox("listBoxID", (MultiSelectList) ViewBag.CodigoClase, htmlAttributes: new { @class= "表单控件列表框; listBoxClass", multiple = "multiple", @rows=20, style="height: 200px; width:100px" })
    @ Html.TextAreaFor(m=>m.CodigoSegmento, new {style="height:200px;width:100px"})

标签: javascript razor listbox textarea selecteditem


【解决方案1】:

使用 append 函数,您可以将内容插入到匹配元素集中每个元素的末尾。所以你不能使用这个函数来改变 textarea 的值。 只需使用以下脚本:

$(".listBoxClass").change(function() {
    $("#textAreaID").val( $( this ).val() )
});
<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>

【讨论】:

  • 如果我需要保留用户之前选择的值怎么办?而且他可以手动添加一些值
  • 保留前一个值:$(".listBoxClass").change(function(){var previous_value =$("#textAreaID").val();$("#textAreaID") .val($(this).val())});
  • 谢谢!!!!它以这种方式工作(创建var previous_value 并使用previous_value 和新选定项目设置文本区域的val)$(".listBoxClass").change(function () { $("#listBoxID option:selected").每个(函数(){ var previous_value = $("#textAreaID").val(); $("#textAreaID").val(previous_value + "\n" + $(this).val()); }) ; }).trigger("改变");
【解决方案2】:

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

$(".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>

【讨论】:

  • 其实我需要查看用户在textArea中选择的所有项目...有什么办法吗?
  • 当然可以,但不是在我在 textarea 上做某事之后(比如删除一个单词,或者只是一个字符)
  • 嗯,你想做的比你原来的问题要多得多......真的不可能知道用户添加了什么以及选择添加了什么。
  • 我只想保留这两个...所选项目和手动插入...可以吗?
  • 您如何知道添加了什么以及删除什么?对此没有简单的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多