【问题标题】:After changing text in textarea is not changing when try to change using drop-down list text?尝试使用下拉列表文本更改时,更改文本区域中的文本后没有更改?
【发布时间】:2020-09-23 11:15:14
【问题描述】:

我有三个多选下拉列表,从这些下拉列表中选择后,用户按下提交按钮,列表文本显示在 textarea 中,但如果用户更改 textarea 中的某些文本,然后再次从下拉列表中选择另一个列表,然后按下提交textarea 中的文本没有变化。 我尝试了一些解决方案,例如那个人说使用$("#total_selections").val(""); 而不是$("#total_selections").html(""); 但在此之后 textarea 中没有显示任何内容。

<div class="form-group">
  <button type="button" class="btn btn-primary" id="selection_button" disabled>Select Tags</button>
 </div>
@Html.TextAreaFor(m => m.Formula, new { @class = "form-control", id = "total_selections" })

$("#selection_button").click(function () {
            $("#tag_creation").prop('disabled', false);
            $("#total_selections").val("");
            SelectedItemArray();
        });
    });


    function SelectedItemArray() {
        var datas = new Array();
        var datas = $('.add_item option:selected').map(function ()
        {
            return $(this).text() || undefined;
            }).get();
        $.ajax({
            url: "@Url.Action("selectedTags","CalculatedTags")",
            type: 'Post',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify({ 'selectedTags': datas }),
            success: function (data) {
                $("#total_selections").append(data);
            }
        });
    }

【问题讨论】:

标签: javascript html jquery asp.net model-view-controller


【解决方案1】:

$("#selection_button").click(function () {
               var  sel = $('#add_item option:selected').val();
     const ele= `<p style = "display:inline; background-color: #e9ebee; color: black; margin: 2px; padding: 1px;"> ${sel} <span style="cursor: pointer" onclick= "this.parentElement.remove()"> x</span> </p>`;
     $("#total_selections").append(ele);
});

   
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select  id="add_item">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

  <button type="button"  id="selection_button" >Select Tags</button>
<div contenteditable="false" style="min-height:50px; border:1px solid black; 
 width:300px;" id="total_selections"></div>

append 函数改变了 DOM,这不是你在这里想要做的(这破坏了 textarea 元素的默认行为)。

【讨论】:

  • 在使用 .val() 时无法在 textarea 中获取 null,但在使用 .text() 或 .html 时获取文本
  • 通过控制台检查选定的值和数据应该可以工作
  • 对不起,我犯了一个愚蠢的错误,我应该使用 $("#total_selections").val(data);而不是这个 $("#total_selections").append(data);
  • 嗨,我还有一个问题,我可以让 Textarea 中的这些选择不可更改吗?我的意思是 saab audi 是不可编辑的,但我们可以在它们之间插入一些东西,例如 saab+audi=car
  • 我没听懂你想说什么!你想让 textarea 只读吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
  • 2011-10-18
  • 1970-01-01
  • 2017-01-09
  • 1970-01-01
相关资源
最近更新 更多